2011-05-01 92 views
0

项目嵌套属性和任务有一个一对多的关系,以及项目accepts_nested_attributes_for:任务。保存阵列accepts_nested_attributes_for

在形式,我的任务对象的样子:

项目[任务] [2] [assigned_time] 项目[任务] [2] [DUE_TIME]

当提交表单时,我得到hash:

参数:{“utf8”=>“✓”,“authenticity_token”=>“... =”,“project”=> {“id”=>“1”,“tasks” => { “1”=> { “assigned_time”=> “09:00”, “DUE_TIME”=> “17:00”}, “2”=> { “assigned_time”=> “09:00”,“ DUE_TIME “=>” 17:00" }}

然后我EXPEC只需保存项目对象即可保存它们: project = Project.find(params [:id])

respond_to do | format | 如果project.update_attributes(PARAMS [:任务])

,但我得到: 警告:不能大规模指派保护的属性:id SQL(0.3ms的)ROLLBACK 在169ms

ActiveRecord的完成: :AssociationTypeMismatch(任务(#2188181260)预期,得到了阵列(#2151973780)):

任何想法如何解决这一问题?

回答

3

在你的Projects模型,accepts_nested_attributes_for :tasks。这将定义@project.tasks_attributes=如果你有一个has_many :tasks协会或@project.task_attributes=如果你有一个has_one :task关联。

在您的形式,如下:

= form_for @project do |f| 
    = f.label :project_attribute 
    = f.text_field :project_attribute 

    = f.fields_for :tasks do |t| 
    = t.label :task_attribute 
    = t.text_field :task_attribute 

在您的项目控制器,如下:

def new 
    @project = Project.new 
    @project.tasks.build #=> if has_many 
    @project.build_task #=> if has_one 
end 
2

我想,你只是忘记添加task_attributes到attr_accessible列表中的项目模型:

attr_accessible :tasks_attributes, ... 

并且也注意到,这,也许你产生错误的形式,因为在我当前的应用程序,表格嵌套属性使用task_attributes方法,而不是任务(如你的散列)

+0

其实我不得不定义task_attributes =。我不完全理解它,但它工作。我很好奇,因为如果有人知道 – 99miles 2011-05-01 17:58:54

+0

添加您的项目模型质疑的解释,请 – crsde 2011-05-01 18:02:32

+0

attr_accessible在导轨4赞成强参数弃用 – 2017-09-25 22:01:41