Rails嵌套属性给出错误:未定义的方法`build_priority'
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Rails嵌套属性给出错误:未定义的方法`build_priority'相关的知识,希望对你有一定的参考价值。
整天但找不到简单的问题。为什么我的嵌套属性不能使用此关联?
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
答案
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
以上是关于Rails嵌套属性给出错误:未定义的方法`build_priority'的主要内容,如果未能解决你的问题,请参考以下文章
尝试使用to_json生成嵌套的json格式时,ruby on rails中的未定义方法错误?
未定义的方法 - 提交表单后属性为 NULL (Rails 3.2.13)