mihai
mihai

Reputation: 38573

Rails has_many association with different condition

In the User class, I have:

has_many :posts, foreign_key: "by_user_id"

This generates the following sql (when I call user.posts)

SELECT "posts".* FROM "posts" 
WHERE "posts"."by_user_id" = 2

How do I define an association that generates the following sql ?

SELECT "posts".* FROM "posts" 
WHERE "posts"."by_user_id" = 2 or "posts"."group_user_id" = 2

The Posts table contains both columns (by_user_id and group_user_id) and group_user_id is also an id of a User.

Upvotes: 1

Views: 64

Answers (2)

mihai
mihai

Reputation: 38573

The solution is to use a class method inside the User model:

def posts
  Post.where('by_user_id = ? or group_user_id = ?', id, id)
end

Upvotes: 0

jbearden
jbearden

Reputation: 1869

Post.where(by_user_id: 2, group_user_id: 2)

Is this what you are looking for?

Upvotes: 1

Related Questions