给出以下模型:
rails g model Menu name:string
rails g model MenuHeader mh_name:string menu_id:integer
class Menu < ActiveRecord::Base
has_many :menu_headers
attr_accessible :menu_headers_attributes, :name
end
class MenuHeader < ActiveRecord::Base
belongs_to :menu
end
尝试添加via rails console,我得到:
Menu.create({"name"=>"My first menu",:menu_headers_attributes=>{:mh_name => "here is my name"}})
ActiveRecord::UnknownAttributeError: unknown attribute: menu_headers_attributes
添加此内容的正确语法是什么?
我可以删除attr_accessible吗?
thx
从bricker的回答中编辑#1(顺便说一下,非常感谢!)
class Menu < ActiveRecord::Base
has_many :menu_headers
attr_accessible :name
accepts_nested_attributes_for :menu_headers
end
ruby-1.9.2-p290 :001 > Menu.create({"name"=>"My first menu",:menu_headers_attributes=>{"mh_name" => "here is my name"}})
TypeError: can't convert Symbol into Integer
from /Users/jt/.rvm/gems/ruby-1.9.2-p290/gems/activerecord-3.1.0/lib/active_record/nested_attributes.rb:395:in `[]'
from /Users/jt/.rvm/gems/ruby-1.9.2-p290/gems/activerecord-3.1.0/lib/active_record/nested_attributes.rb:395:in `block in assign_nested_attributes_for_collection_association'
from /Users/jt/.rvm/gems/ruby-1.9.2-p290/gems/activerecord-3.1.0/lib/active_record/nested_attributes.rb:395:in `map'
from /Users/jt/.rvm/gems/ruby-1.9.2-p290/gems/activerecord-3.1.0/lib/active_record/nested_attributes.rb:395:in `assign_nested_attributes_for_collection_association'
from /Users/jt/.rvm/gems/ruby-1.9.2-p290/gems/activerecord-3.1.0/lib/active_record/nested_attributes.rb:287:in `menu_headers_attributes='
from /Users/jt/.rvm/gems/ruby-1.9.2-p290/gems/activerecord-3.1.0/lib/active_record/base.rb:1745:in `block in assign_attributes'
答案 0 :(得分:1)
您需要添加:
accepts_nested_attributes_for :menu_headers
进入您的菜单模型。这会将menu_headers_attributes
作为属性添加到Menu
。