Conditions => Or instead of AND

Hello,

I have in my User model.

belongs :groups

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”]

…but this add AND between the conditions and not OR?

I hope someone can tell me how to change the AND to OR in the belongs
and thanks for your help:)

Group.find(:all, :conditions => [“user_id IS NULL OR user_id = ?”,
user.id])

Rick DeNatale

My blog on Ruby
http://talklikeaduck.denhaven2.com/

Thanks for your answer Rick.

I just ended up doing what you just did in the end of your post.

Group.find(:all, :conditions => [“user_id IS NULL OR user_id = ?”,
user.id]

On 10/14/07, Jamal S. [email protected] 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/

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