-1
class User < ActiveRecord::Base
  has_many :tasks
  has_many :task_items, through: :task
  accepts_nested_attributes_for :task
  accepts_nested_attributes_for :task_item
end

class Task < ActiveRecord::Base
 belongs_to :user
 has_many :task_item
end

class TaskItem < ActiveRecord::Base
  belongs_to :task
end

我可以在用户表单中使用 form_for 获取并保存任务的表单数据。

<%= fields_for :user, user do |f| -%>
 <%= f.fields_for :task do |builder| %>
  <%=builder.text_field :name%>
<%end%>
<% end %>

我想使用 form_for 在用户表单本身中接受 Task 和 TaskItem 的属性。无法弄清楚如何做到这一点。

我试过:

<%= fields_for :user, user do |f| -%>
 <%= f.fields_for :task do |builder| %>
   <%=builder.text_field :name%>
   <%= f.fields_for builder.object.checklist do |builder_1| %>
     <%builder_1.object.each do |bb|%>
      <%= bb.check_box :completed%>
     <%end%>
   <%end%>
 <%end%>

它为#我希望能够创建一个用户,它的任务和任务项记录都使用一个表单提供了未定义的方法“check_box”。欢迎任何解决方案。

4

1 回答 1

0

你有很多复数错误。检查这些更改:

class User < ActiveRecord::Base
  has_many :tasks
  has_many :task_items, through: :tasks     #not task
  accepts_nested_attributes_for :tasks      #not task
  accepts_nested_attributes_for :task_items #not task_item
end

class Task < ActiveRecord::Base
 belongs_to :user
 has_many :task_items #not task_item
end

class TaskItem < ActiveRecord::Base
  belongs_to :task
end

然后,观点:

<%= fields_for :user, user do |f| %>
  <%= f.fields_for :tasks do |builder| %>
    <%= builder.text_field :name %>
    <%= builder.fields_for :task_items do |ti| %>
      <%= ti.check_box :completed %>
    <% end %>
  <% end %>
<% end %>
于 2018-09-03T01:45:54.487 回答