Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: has_many through with polymorphic association - will this work?

A Person can have many Events and each Event can have one polymorphic Eventable record. How do I specify the relationship between the Person and the Eventable record?

Here are the models I have:

class Event < ActiveRecord::Base   belongs_to :person   belongs_to :eventable, :polymorphic => true end  class Meal < ActiveRecord::Base   has_one :event, :as => eventable end  class Workout < ActiveRecord::Base   has_one :event, :as => eventable end 

The main question concerns the Person class:

class Person < ActiveRecord::Base   has_many :events   has_many :eventables, :through => :events  # is this correct??? end 

Do I say has_many :eventables, :through => :events like I did above?

Or do I have to spell them all out like so:

has_many :meals, :through => :events has_many :workouts, :through => :events 

If you see an easier way to accomplish what I'm after, I'm all ears! :-)

like image 888
Finch Avatar asked Aug 09 '11 13:08

Finch


People also ask

What is Rails polymorphic association?

Polymorphic relationship in Rails refers to a type of Active Record association. This concept is used to attach a model to another model that can be of a different type by only having to define one association.

How is polymorphic association set up 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 association in Ruby on Rails?

Association in Rails defines the relationship between models. It is also the connection between two Active Record models. To figure out the relationship between models, we have to determine the types of relationship.


1 Answers

You have to do:

class Person < ActiveRecord::Base   has_many :events   has_many :meals, :through => :events, :source => :eventable,     :source_type => "Meal"   has_many :workouts, :through => :events, :source => :eventable,     :source_type => "Workout" end 

This will enable you to do this:

p = Person.find(1)  # get a person's meals p.meals.each do |m|   puts m end  # get a person's workouts p.workouts.each do |w|   puts w end  # get all types of events for the person p.events.each do |e|   puts e.eventable end 
like image 110
Rob Sobers Avatar answered Sep 20 '22 08:09

Rob Sobers