Has Many and finding unused options

I’ve got a user model and a policy model. I’ve got the association
set up so that both use the has_many :through syntax. Given the
scenario in editing a policy, a couple of users are already assigned.
How can I figure out what users are not assigned to that policy
already? Thanks


Marlon

Marlon M. wrote:

I’ve got a user model and a policy model. I’ve got the association
set up so that both use the has_many :through syntax. Given the
scenario in editing a policy, a couple of users are already assigned.
How can I figure out what users are not assigned to that policy
already? Thanks


Marlon

Let’s say you have your policy object in @policy

@unassigned_users = User.find(:all).collect {|u| u unless
@policy.users.include?(u)}

This line should populate @unassigned_users as an array of User objects
which are not currently linked to @policy.

How it works (in case you want to know)…
1.The .collect method steps through a collection, executes the
associated block of code for each item in the collection, and returns an
array of all the values returned by the block. The |u| in the block maps
to each user object returned by User.find(:all)

[email protected] returns the collection of User objects linked to
@policy.

3.The .include? method returns true if the value in the parentheses (in
this case a User object) exists in the collection on which you are
executing the method (in this case, @policy.users). For our purposes
here, if it returns true, the block does nothing, otherwise the block
returns the User object, which ends up in the @unassigned_users array.

c.

excellent…it never fails to amaze me how powerful ruby/rails really
is.

On 11/9/06, Cayce B. [email protected] wrote:


How it works (in case you want to know)…
executing the method (in this case, @policy.users). For our purposes
here, if it returns true, the block does nothing, otherwise the block
returns the User object, which ends up in the @unassigned_users array.

c.


Posted via http://www.ruby-forum.com/.


Marlon

Yeah, block programming (something I’d never heard of before Ruby/Rails)
is pure gold.

c.