【问题标题】:Rails polymorphic association accepts_nested_attributesRails 多态关联 accept_nested_attributes_for
【发布时间】:2016-07-07 03:30:02
【问题描述】:

我目前是这样设置的多态关联

class Reading < ApplicationRecord
   has_one :audio, as: :audioable
   accepts_nested_attributes_for :audio
end

class Audio < ApplicationRecord
   belongs_to :audioable, polymorphic: true
end

在我的 RSPEC 测试中,我设置了这个

@reading = attributes_for(:reading, creator: @user, body: "who let the dogs out? Must be me\n\nMeMeMe")
@reading[:audio_attributes] = attributes_for(:audio)

但是,当我将此 @reading 发布到 reading#create 控制器时出现以下错误

{:errors=>{:"audio.audioable"=>["must exist"]}}

对于非多态关联,我已经使用inverse_of 创建了父资源和嵌套资源,但我不确定如何为多态关联创建它。

【问题讨论】:

    标签: ruby-on-rails polymorphism


    【解决方案1】:

    inverse_of 不能用于多态关联,您是否看过 Single Table Inheritance,这可能是一个很好的解决方案,具体取决于您要实现的目标

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-23
      • 2019-03-14
      • 2016-04-05
      • 1970-01-01
      相关资源
      最近更新 更多