开发者

Rails 3 syntax with attr_accessible and creating associated objects

Given following model:

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

Trying to add via rails console, I get:

Menu.create({"name"=>"My first menu",:menu_headers_attributes=>{:mh_name => "here is my name"}})
ActiveRecord::UnknownAttributeError: unknown attribute: menu_headers_attributes

What would be the correct syntax for adding this?

Could I remove the attr_accessible?

thx

edit #1 from bricker's answer (thx btw, really appreciate!)

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'


You need to add:

accepts_nested_attributes_for :menu_headers

into your Menu model. That will add the menu_headers_attributes as an attribute to Menu.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜