本文介绍了扶手:的has_many通过与多态关联 - 将这项工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
A 人
可以有多个活动
,每个事件
可以有一个多态 Eventable
记录。如何指定关系的人
和 Eventable
记录?
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?
下面是我的模型:
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
主要的问题是关于人
类:
class Person < ActiveRecord::Base
has_many :events
has_many :eventables, :through => :events # is this correct???
end
我说的has_many:eventables,:通过=&GT; :?事件
像我上面
还是我必须拼他们全力以赴,像这样:
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! :-)
推荐答案
您需要做的:
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
这篇关于扶手:的has_many通过与多态关联 - 将这项工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!