【问题标题】:Rails nested attributes giving error: undefined method `build_priority'Rails嵌套属性给出错误:未定义的方法`build_priority'
【发布时间】:2017-12-28 16:29:52
【问题描述】:

整天但找不到简单的问题。为什么我的嵌套属性不适用于此关联?

Here is error: NoMethodError (undefined method `build_priority' for
#<Audit:0x134234jnjn2j>):   app/controllers/audits_controller.rb:43:in `new'

audits_controller.rb

 def new
    @audit = Audit.new
    @audit.build_priority 
 end

audit.rb 模型

  has_many :priorities, dependent: :destroy
  accepts_nested_attributes_for :priorities, allow_destroy: true, reject_if: :all_blank

priority.rb 模型

class Priority < ActiveRecord::Base
  belongs_to :audit
  accepts_nested_attributes_for :audit, allow_destroy: true, reject_if: :all_blank
end

【问题讨论】:

  • 给定的答案对您有帮助吗?

标签: ruby-on-rails ruby-on-rails-4 associations nested-forms has-many


【解决方案1】:
 def new
    @audit = Audit.new
    @audit.priorities.build
 end

型号:-

class Audit < ActiveRecord::Base
  has_many :priorities, dependent: :destroy
  accepts_nested_attributes_for :priorities, allow_destroy: true, reject_if: :all_blank

end

class Priority < ActiveRecord::Base
  belongs_to :audit
  #accepts_nested_attributes_for :audit, allow_destroy: true, reject_if: :all_blank
end

【讨论】:

  • 现在给出:“关联:未找到优先级”。 @Gabbar
  • Audit 模型中有priority_id 字段吗?你的AuditPriority 模型是如何关联的?
  • 审核 has_many 优先级,因此不需要“priority_id”。但是每个优先级都有“audit_id”。您可以查看相关关联。
  • @DanielsV 查看最近所做的更改并重新启动服务器并尝试
  • @DanielsV 让我知道以获得进一步的指导。如果有帮助,请随时接受赞成的答案
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-11
相关资源
最近更新 更多