33

There are 2 models, and they are linked using a has_many :though relation.

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?

Tiago
  • 2,966
  • 4
  • 33
  • 41
  • 1
    Possible duplicate of [Rails has\_many :through Find by Extra Attributes in Join Model](http://stackoverflow.com/questions/408872/rails-has-many-through-find-by-extra-attributes-in-join-model) – DreadPirateShawn Oct 06 '15 at 05:45
  • Seems to be related to this question, which has a good answer => http://stackoverflow.com/questions/408872/rails-has-many-through-find-by-extra-attributes-in-join-model – Jochen Nov 06 '10 at 22:51

2 Answers2

38

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
msanteler
  • 2,163
  • 1
  • 16
  • 21
  • Bear in mind that answer is from 2009 (the linked answer). `:conditions => ['event_users.active = ?',true]` was how things were done before Rails 3. – Luca Spiller Aug 23 '14 at 08:13
  • 3
    I'm not criticizing, just trying to provide an up-to-date answer for anyone who finds their way here looking for one – msanteler Aug 25 '14 at 14:05
  • 1
    it there a way to do this without explicitly defining `game_likes`?, i mean just with conditions on `liked_games` – Yossi Shasho Oct 13 '14 at 13:12
19

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
littleforest
  • 2,057
  • 21
  • 29
  • 1
    the question is how to create record with this condition using simple_form – Yakob Ubaidi Mar 23 '17 at 00:18
  • 1
    What is the use of `:source` attribute? – Mohamed AbuIssa Nov 27 '20 at 05:08
  • Rails doesn't know which field to use on the `game_users` table to make the association with, since `liked_games` doesn't match any foreign keys on the `game_users` table. So you have to tell it to use the `game_id` field by specifying `source: :game`. – littleforest Nov 27 '20 at 19:48