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?
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With