gpt4 book ai didi

ruby-on-rails - rails : has_many through with polymorphic association - will this work?

转载 作者:行者123 更新时间:2023-12-03 07:25:24 30 4
gpt4 key购买 nike

一个可以有许多事件,每个事件可以有一个多态Eventable记录。如何指定 PersonEventable 记录之间的关系?

这是我拥有的模型:

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

主要问题涉及 Person 类:

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

我是否像上面那样说has_many :eventables, :through => :events

或者我必须像这样把它们全部拼写出来:

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

如果您发现一种更简单的方法来完成我所追求的目标,我洗耳恭听! :-)

最佳答案

你必须做:

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

这将使您能够执行以下操作:

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

关于ruby-on-rails - rails : has_many through with polymorphic association - will this work?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6997141/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com