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
I am able to get & save form data for Task using form_for in the user form.
<%= fields_for :user, user do |f| -%>
<%= f.fields_for :task do |builder| %>
<%=builder.text_field :name%>
<%end%>
<% end %>
I want to accept attributes for Task as well as TaskItem in the User form itself using form_for. Unable to figure out how to do this.
I tried with:
<%= 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%>
It gives undefined method `check_box' for # I want to be able to create a User,its task & task item records all using one form. Any solutions are welcome.
You have many pluralization errors. Check these changes:
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
Then, the view:
<%= 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 %>