Ruby-on-rails rails has_many :through - 是否可以在直通表中有条件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4115554/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
rails has_many :through - Is it possible to have a conditions in the through table?
提问by Tiago
There are 2 models, and they are linked using a has_many :though relation.
有 2 个模型,它们使用 has_many :though 关系链接。
There is the :conditions parameter, that will look for a condition in the other model table, but is there someway to create a condition in the join table?
有 :conditions 参数,它将在另一个模型表中查找一个条件,但是有没有办法在连接表中创建一个条件?
For example, supose I have:
例如,假设我有:
User
Game
GameUser
One User may have many games, as a Game may have many users. But i want to store extra information in the joint table, for example if the user likes or not that game.
一个用户可能有很多游戏,因为一个游戏可能有很多用户。但是我想在联合表中存储额外的信息,例如用户是否喜欢该游戏。
And I would like to have a relation filter in my User model, something like this:
我想在我的用户模型中有一个关系过滤器,如下所示:
has_many :games, :through => 'game_users'
has_many :liked_games, :through => 'game_users', :conditions_join => { :like => true }
Is there a pretty way to have this functionality?
有没有一种很好的方法来拥有这个功能?
回答by msanteler
Jochen's link has a good solution – but :conditionsis deprecated and the :conditions => ['event_users.active = ?',true]bit just doesn't seem very rails. Try this:
Jochen 的链接有一个很好的解决方案——但:conditions已被弃用,而且这:conditions => ['event_users.active = ?',true]一点似乎不太合理。尝试这个:
has_many :game_users
has_many :game_likes, -> { where like: true }, class_name: 'GameUser'
has_many :liked_games, :through => :game_likes, class_name: 'Game', :source => :game
回答by littleforest
In Rails 4 you can do:
在 Rails 4 中,您可以执行以下操作:
# app/models/user.rb
has_many :liked_games, -> { where(like: true) }, class_name: "Game",
through: :game_users, source: :game

