How do I list items not 'joined' to the current record?

My HABTM joins seem to be working for the most part. Yes! Now I’m trying
to create two lists on my project page of joined and unjoined contacts.

To list the contacts that are joined to my project I use:
<% mycontacts = @project.contacts %>
then use a for loop to display a checkbox next to each record so I can
select it to un-join them.

I’m stumped on how to list contacts that are not joined though. I’d like
to have checkboxes next to them so they can be added to the joined list.
Eventually I also hoping to have multiple lists of un-joined contacts
for contractors, developers, designers, and such which can be added to
the project (filtering the not joined contacts by role).

This starts to work when first loaded but then after addding contacts it
no longer discriminates and trying to unjoin previous selections stops
working. Hard coding the project_id won’t work in the final also:
<% mycontacts = Contact.find(:all, :joins => ‘INNER JOIN
contacts_projects ON contacts.id != contacts_projects.contact_id WHERE
(contacts_projects.project_id = 3 )’ ) %>

Any help appreaciated. Maybe there are some more in-depth HABTM
tutorials posted somewhere?

DAN

Something along the lines of

Contact.find :all, :joins => ‘LEFT OUTER JOIN contacts_projects on
contacts.id = contacts_projects.contact_id’, :conditions =>
‘contacts_projects.project_id IS NULL’

should get you all contacts which don’t have any projects assigned to
them.
Fred

Just grab all contacts, and filter out the ones that are included in the
current project’s contacts. As in…

not_my_contacts = Contact.find(:all).collect {|c| c unless 

@project.contacts.include?© }

This could be expanded for your future needs…

not_my_developers = Contact.find(:all, :conditions => "role = 

‘DEVELOPER’").collect {|c| c unless @project.contacts.include?© }

etc.

c.

Hi Dan

I’ve seen your old post on the rails:talk. I’ve had a similar problem
and was able to solve it like this:
@users_not_of_group = User.find_by_sql([“select * from users where
id not in (select user_id from groups_users where group_id = ?)”,
params[:id]])
–> this gives me all users that are not assigned to a particular
group

The other method with the filtering did not work for me, I got an
error about nil-objects. I don’t exactly understand the syntax though,
my ruby is not so good. It would be very elegant though, I wish I
could get it to work.

best regards
paul

ps I meant to post this on your thread, but somehow I could only
answer to you personally, (thread too old?)

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs