如何正确配置 rails 3 嵌套属性



我有 2 个模型。会员和调查

成员.rb 如下

Class Member < ActiveRecord::Base
  has_one :survey, :dependent => :destroy
  accepts_nested_attributes_for :survey
  attr_accessible :fname,:lname, :address, :city, :state, :zip, :email, :phone, :phone_alt, :e_contact, :e_contact_phone, :physician, :physician_phone, :chiropractor, :chiropractor_phone, :password, :password_confirmation, :remember_me, :survey_attributes
end

调查.rb 如下

Class Survey < ActiveRecord::base
  belongs_to :member
end

但是,每当我尝试使用我收到的调查属性创建成员时

活动模型::批量分配安全性::

错误:无法批量分配受保护的属性:调查

我正在通过控制台对此进行测试。

对于has_one关联,可访问调用应为:

attr_accessible :survey_attributes

您发布的参数需要嵌套,如下所示:

params = { :member => { :name => 'Jack', :survey_attributes => { :attribute => 'value' } } }

在表单中,请确保您正确构建嵌套关系,即您必须使用:

= form_for @member do |f|
  ...
  = f.fields_for :survey do |s|
    ...

如果你有这些东西设置,那么它应该可以工作。如果这没有捕获您的错误,那么请在控制台中显示您正在尝试并且不起作用的日志。

有关更多信息,请参阅 Rails API 中的 #accepts_nested_attributes_for。

最新更新