开发者

rails has_many :through - Is it possible to have a conditions in the through table?

There are 2 models, and they are linked using a has_many :though r开发者_开发知识库elation.

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?

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?


Jochen's link has a good solution – but :conditions is deprecated and the :conditions => ['event_users.active = ?',true] bit just doesn't seem very rails. Try this:

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


In Rails 4 you can do:

# app/models/user.rb

has_many :liked_games, -> { where(like: true) }, class_name: "Game", 
  through: :game_users, source: :game
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜