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获取并保存Task的表单数据。
<%= 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' 我希望能够创建一个User,其任务和任务项记录全部使用一种形式。 欢迎任何解决方案。
答案 0 :(得分: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 %>