简体   繁体   English

使用 accept_nested_attributes_for 保存嵌套属性数组

[英]Saving array of nested attributes with accepts_nested_attributes_for

Project and tasks have a one-to-many relationship, and project accepts_nested_attributes_for:tasks .项目和任务是一对多的关系,项目接受accepts_nested_attributes_for:tasks

In the form, my task objects look like:在表单中,我的任务对象如下所示:

project[tasks][2][assigned_time]
project[tasks][2][due_time]

When the form is submitted I get a hash like:提交表单后,我得到一个 hash ,例如:

Parameters: {"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"}}参数:{"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 "}}

Then I expect them to be saved by just saving the project object:然后我希望通过保存项目 object 来保存它们:

project = Project.find(params[:id])

respond_to do |format|
  if project.update_attributes(params[:tasks])

But I get:但我得到:

WARNING: Can't mass-assign protected attributes: id SQL (0.3ms) ROLLBACK Completed in 169ms警告:无法批量分配受保护的属性:id SQL(0.3 毫秒)回滚在 169 毫秒内完成

ActiveRecord::AssociationTypeMismatch (Task(#2188181260) expected, got Array(#2151973780)): ActiveRecord::AssociationTypeMismatch(预期任务(#2188181260),得到数组(#2151973780)):

Any ideas how to fix this?任何想法如何解决这一问题?

In your Projects model, accepts_nested_attributes_for:tasks .在您的Projects model 中,接受_nested_attributes_for accepts_nested_attributes_for:tasks This will define @project.tasks_attributes= if you have a has_many:tasks association or @project.task_attributes= if you have a has_one:task association.这将定义@project.tasks_attributes=如果您有has_many:tasks关联或@project.task_attributes=如果您有has_one:task关联。

In your form, the following:在您的表格中,以下内容:

= 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

In your projects controller, the following:在您的项目 controller 中,以下内容:

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

I think, you just forget to add task_attributes to attr_accessible list in your Project model:我认为,您只是忘记将 task_attributes 添加到项目 model 中的 attr_accessible 列表中:

attr_accessible :tasks_attributes, ...

And also, note, that, maybe you generating wrong form, because in my current application, form with nested attributes uses task_attributes method, not tasks (like in your hash)另外,请注意,也许您生成了错误的表单,因为在我当前的应用程序中,具有嵌套属性的表单使用 task_attributes 方法,而不是任务(如在您的哈希中)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM