简体   繁体   中英

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.

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

这是你想要的?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM