On 10/14/07, Jamal Soueidan
<rails-mailing-list-ARtvInVfO7ksV2N9l4h3zg@public.gmane.org>
wrote:>
> Hello,
>
> I have in my User model.
Let''s step back a bit.
> belongs :groups
I think you mean
belongs_to :group
This means that AR is expecting your User table to have a foreign key
to the Group table with the name group_id
With this association a user is associated with a single group.
> I want to put condition on it so it end of like this
>
> SELECT * FROM groups WHERE (groups.user_id = 2 OR (groups.user_id is
> NULL)
>
> ...so I thought this would do that
>
> belongs :groups, :conditions => ["groups.user_id is NULL"]
The condition on an association declaration adds additional
restrictions on what will be returned on the query. with a belongs_to
:group association, you get a group (not groups) method which returns
at most one group. If effectively does Group.find(group_id).
It seems like you''re modeling this wrong.
What are the real-world relationships between user and groups?
If a group can have more than one user (seems likely) then you want a
has_many relationship back to user. This still would not requre a
user_id column in group.
If, on the other hand, you want some groups to belong to a single user
then group should have a belongs_to :user, and a user_id column
If the user table has a user_id column then to find groups which
belong to either a particular user or no-one you can do something
like:
Group.find(:all, :conditions => ["user_id IS NULL OR user_id = ?",
user.id])
--
Rick DeNatale
My blog on Ruby
http://talklikeaduck.denhaven2.com/
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups
"Ruby on Rails: Talk" group.
To post to this group, send email to
rubyonrails-talk-/JYPxA39Uh5TLH3MbocFFw@public.gmane.org
To unsubscribe from this group, send email to
rubyonrails-talk-unsubscribe-/JYPxA39Uh5TLH3MbocFFw@public.gmane.org
For more options, visit this group at
http://groups.google.com/group/rubyonrails-talk?hl=en
-~----------~----~----~----~------~----~------~--~---