0
考慮以下模型:Rails 3的語法與attr_accessible和創建關聯的對象
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
嘗試通過鐵軌控制檯添加,我得到:
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
編輯#1從布里克的回答(THX順便說一句,真的很感謝!)
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'
thx - 進一步,但得到一個新的錯誤 – timpone