0

我是全新的 Rails 新手,如果这是一个愚蠢的问题,请原谅我——我根本无法拼凑足够的答案来判断我是否开始错误。开始。

  1. 我创建了与我的Company模型相关的所有内容rails g scaffold Company name:string description:text location_city:string location_state:string accounttype:references

  2. 我创建了与Accounttype模型相关的所有内容rails g scaffold Accounttype id:primary_key name:string price:decimal

  3. 因此,我的Company模型包含以下津贴:

    belongs_to :accounttype

    attr_accessible :description, :location_city, :location_state, :name

  4. 当我转到我为公司生成的脚手架编辑表单并在这些字段中输入数据时,它会引发错误:Can't mass-assign protected attributes: accounttype

  5. 如果我添加:accounttypeattr_accessible,它会抛出Accounttype(#70175254242100) expected, got String(#70175215042700)以下请求参数:

    {"utf8"=>"✓", "authenticity_token"=>"oXm3cqo0jemKYFB5OGqn5ixXLSB+bH19/1RhPUu0ZHU=", "company"=>{"name"=>"Acme Corp", "description"=>"a", "location_city"=>"san diego", "location_state"=>"california", "accounttype"=>"1"}, "commit"=>"Create Company"}

那么,是我用来:references链接这两个模型的问题吗?如果我使用它没问题,那么我应该怎么做才能让创建/更新工作?

4

2 回答 2

1

恭喜您使用了学习轨!您必须accepts_nested_attributes_forCompany模型中使用才能将属性直接分配给Accounttype模型。像这样:

belongs_to :accounttype

accepts_nested_attributes_for :accounttype

attr_accessible :description, :location_city, :location_state, :name, :accounttypes_attributes

请注意,由于您使用的是 attr_accessible 您必须添加accounttypes_attributes 另外,我建议更改AccounttypeAccountType

资料来源:文档 Railscast

于 2012-12-19T07:05:12.957 回答
0

您应该研究资源嵌套和嵌套资源的使用

accept_attributes_for :accounttype

http://masonoise.wordpress.com/2010/07/23/rails-and-forms-using-accepts_nested_attributes_for/

于 2012-12-19T07:01:39.030 回答