【问题标题】:Rails Polymorphic associations with name spaceRails 与命名空间的多态关联
【发布时间】:2016-09-15 14:12:48
【问题描述】:

我想保存不同的结果(默认和手动),每个结果都有一个原因。认为这将是一个多态关联的好地方。然而,模型是命名空间的,事实证明这比预期的要复杂。关注the guide

app/models/event/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

app/models/event/result.rb

class Event::Result < ActiveRecord::Base
  belongs_to :event
  has_one :event_reason, as: :reasonable
end

app/models/event/manual_result.rb

class Event::ManualResult < ActiveRecord::Base
  belongs_to :event
  has_one :event_reason, as: :reasonable
end

但如果我尝试做类似的事情:

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

 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

似乎期望关联嵌套在附加层 Event::ManualResult::EventReasonEvent::Result::EventReason

【问题讨论】:

    标签: ruby-on-rails ruby polymorphic-associations model-associations


    【解决方案1】:

    你只需要在关联上指定class_name:

    class Event::Result < ActiveRecord::Base
      belongs_to :event
      has_one :event_reason, as: :reasonable, class_name: 'Event::Reason'
    end
    

    这样你就不允许 Rails 尝试从 .event_reason 中为你猜测类(在这种情况下它无法做到)。

    【讨论】:

    • 谢谢老兄!伙计,我真的只是做了同样的事情!蜂巢五。真是脑筋急转弯
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-05-28
    • 2014-03-15
    • 2017-11-30
    • 1970-01-01
    • 1970-01-01
    • 2014-09-21
    • 1970-01-01
    相关资源
    最近更新 更多