In my Rails app I have a nested form_for
in my show action. This form is the same as the one in the edit action, but it has different fields.
Category -> Task -> completed (boolean, check_box)
is what I am trying to update, but it doesn't. Although, if I do Category -> Task -> name (string, text_field)
it updates fine.
This does NOT work
<%= form_for check_list do |f| %>
<%= f.error_messages %>
<% count = 0 %>
<ol>
<%= f.fields_for :tasks do |task| %>
<li>
<%= task.label :completed, check_list.tasks[count].name %>
<%= task.check_box :completed %>
</li>
<% count += 1 %>
<% end %>
</ol>
<p><%= f.submit 'Update' %></p>
<% end %>
This works
<%= form_for check_list do |f| %>
<%= f.error_messages %>
<% count = 0 %>
<ol>
<%= f.fields_for :tasks do |task| %>
<li>
<%= task.label :name, check_list.tasks[count].name %>
<%= task.text_field :name %>
</li>
<% count += 1 %>
<% end %>
</ol>
<p><%= f.submit 'Update' %></p>
<% end %>
This is a partial, and check_list
is a variable I'm pas开发者_如何学JAVAsing
Edit: Here is the source for my models:
class CheckList < ActiveRecord::Base
has_many :tasks, :dependent => :destroy
accepts_nested_attributes_for :tasks, :reject_if => lambda { |a| a[:name].blank? }, :allow_destroy => true
# Validations
validates :name, :presence => true
end
class Task < ActiveRecord::Base
belongs_to :check_list
end
I'd suggest adding the name as a hidden field on the form, as Rails probably updates all the fields that are passed into the Action.
<%= form_for check_list do |f| %>
<%= f.error_messages %>
<% count = 0 %>
<ol>
<%= f.fields_for :tasks do |task| %>
<li>
<%= task.label :completed, check_list.tasks[count].name %>
<%= task.check_box :completed %>
<%= task.hidden_field :name %>
</li>
<% count += 1 %>
<% end %>
</ol>
<p><%= f.submit 'Update' %></p>
<% end %>
<% end %>
</ol>
<p><%= f.submit 'Update' %></p>
<% end %>
精彩评论