rails has_many:through - 是否可以在直通表中有条件?

Tia*_*ago 22 ruby-on-rails has-many-through ruby-on-rails-3

有两个模型,它们使用has_many:尽管关系链接.

有条件参数,它将在另一个模型表中查找条件,但是在某种程度上是否在连接表中创建条件?

例如,我有:

User
Game
GameUser
Run Code Online (Sandbox Code Playgroud)

一个用户可能有很多游戏,因为游戏可能有很多用户.但我想在联合表中存储额外的信息,例如,如果用户喜欢或不喜欢该游戏.

我希望在我的用户模型中有一个关系过滤器,如下所示:

has_many :games, :through => 'game_users'   
has_many :liked_games, :through => 'game_users', :conditions_join => { :like => true }
Run Code Online (Sandbox Code Playgroud)

有没有一种很好的方法来实现这个功能?

msa*_*ler 23

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
Run Code Online (Sandbox Code Playgroud)

  • 我并不是在批评,只是想为在这里找到自己的路的任何人提供最新答案 (2认同)

lit*_*est 11

在Rails 4中,您可以:

# app/models/user.rb

has_many :liked_games, -> { where(like: true) }, class_name: "Game", 
  through: :game_users, source: :game
Run Code Online (Sandbox Code Playgroud)