Fin*_*nch 39 activerecord ruby-on-rails has-many-through polymorphic-associations
A Person可以有很多Events,每个都Event可以有一个多态Eventable记录.如何指定记录Person与Eventable记录之间的关系?
以下是我的模型:
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
Run Code Online (Sandbox Code Playgroud)
主要问题涉及到Person班级:
class Person < ActiveRecord::Base
has_many :events
has_many :eventables, :through => :events # is this correct???
end
Run Code Online (Sandbox Code Playgroud)
我是否has_many :eventables, :through => :events像上面那样说?
或者我必须像这样拼写它们:
has_many :meals, :through => :events
has_many :workouts, :through => :events
Run Code Online (Sandbox Code Playgroud)
如果你看到一种更简单的方法来完成我所追求的目标,我会全都耳朵!:-)
Rob*_*ers 69
你必须做:
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
Run Code Online (Sandbox Code Playgroud)
这将使您能够这样做:
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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9897 次 |
| 最近记录: |