I have the following:
class Person < ActiveRecord::Base
has_many :tasks
end
class Task < ActiveRecord::Base
belongs_to :person
end
I have no trouble creating new tasks for a person, but it gets hard when trying to update a taks.
At the begining I had a partial for both actions:
<%= form_for([@person, @person.tasks.build]) do |f| %>
# Form stuff
<%= f.submit "Guardar", :class => 'btn'%>
<% end %>
but it kept creating new objects when trying to update. So I created separated forms for create and update, and the second one is something like this:
<%= form_for([@person, @task], :url => {:action => :update} ) do |f| %>
# Form stuff
<%= f.submit "Guardar", :class => 'btn'%>
<% end %>
My question is, Is there a way of doing both things with only one form? How does it knows when to create or update when using a single model?
Yes there is. They are called nested attributes. This rails cast goes over the basics of how to implement nested attributes in your application:
http://railscasts.com/episodes/196-nested-model-form-part-1