The*_*end 4 ruby ruby-on-rails polymorphic-associations model-associations
我想保存不同的结果(默认和手动),每个结果都有原因.认为这将是多态关联的好地方.然而,这些模型是命名空间的,这是一个比预期更加苛刻的方法.按照指南
应用程序/模型/事件/ reason.rb
# id :integer not null, primary key
# reasons :string
# reasonable_id :integer
# reasonable_type :string
# created_at :datetime not null
# updated_at :datetime not null
#
class Event::Reason < ActiveRecord::Base
belongs_to :reasonable, polymorphic: true
end
Run Code Online (Sandbox Code Playgroud)
应用程序/模型/事件/ result.rb
class Event::Result < ActiveRecord::Base
belongs_to :event
has_one :event_reason, as: :reasonable
end
Run Code Online (Sandbox Code Playgroud)
应用程序/模型/事件/ manual_result.rb
class Event::ManualResult < ActiveRecord::Base
belongs_to :event
has_one :event_reason, as: :reasonable
end
Run Code Online (Sandbox Code Playgroud)
但是,如果我尝试做类似的事情:
Event::ManualResult.last.event_reason
Event::ManualResult Load (5.1ms) SELECT "event_manual_results".* FROM "event_manual_results" ORDER BY "event_manual_results"."id" DESC LIMIT 1
NameError: uninitialized constant Event::ManualResult::EventReason
Run Code Online (Sandbox Code Playgroud)
要么
Event::Result.last.event_reason
Event::Result Load (0.4ms) SELECT "event_results".* FROM "event_results" ORDER BY "event_results"."id" DESC LIMIT 1
NameError: uninitialized constant Event::Result::EventReason
Run Code Online (Sandbox Code Playgroud)
这似乎是期待协会嵌套产生额外层内Event::ManualResult::EventReason和Event::Result::EventReason
您只需要在关联上指定class_name:
class Event::Result < ActiveRecord::Base
belongs_to :event
has_one :event_reason, as: :reasonable, class_name: 'Event::Reason'
end
Run Code Online (Sandbox Code Playgroud)
这样你就不允许rails试图从.event_reason中猜出你的类(在这种情况下它无法做到).
| 归档时间: |
|
| 查看次数: |
536 次 |
| 最近记录: |