Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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?

like image 691
Tiago Avatar asked Nov 06 '10 22:11

Tiago


People also ask

Has many through association with example?

In the Doctor model we are saying that the doctor has many appointments and at the same time has many patients but only because he/she has appointments. A doctor can't have any patients without there being an appointment to bring the them together. In the Patient model we are saying the same thing.

What is polymorphic association in Rails?

In Ruby on Rails, a polymorphic association is an Active Record association that can connect a model to multiple other models. For example, we can use a single association to connect the Review model with the Event and Restaurant models, allowing us to connect a review with either an event or a restaurant.

What is has_ many?

A has_many association is similar to has_one , but indicates a one-to-many connection with another model. You'll often find this association on the "other side" of a belongs_to association. This association indicates that each instance of the model has zero or more instances of another model.


2 Answers

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 
like image 135
msanteler Avatar answered Sep 23 '22 08:09

msanteler


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 
like image 26
littleforest Avatar answered Sep 23 '22 08:09

littleforest