Rails: how to save form data after posting
When I use form_for :model
the data is saved when I submit the form.
However when I use form_tag
, the da开发者_运维知识库ta is lost after the form is processed.
I need to use form_tag
because I have two models in one form.
Is there a way to save form data with form_tag
?
You are making two incorrect assumptions in your question. First, form_tag
is not necessary or even recommended for multiple-model forms; Second, form_tag
doesn't do anything fundamentally different from form_for
, you are most likely not formatting the field names correctly for your controller.
In order to create a form with nested models, you need to use the fields_for
helper in conjunction with form_for
. The relationship needs to be defined first in the model with accepts_nested_attributes_for
. Since you have not given us any information about your models, I will give you a made-up example:
class Person < ActiveRecord::Base
has_one :address
accepts_nested_attributes_for :address
end
class Address < ActiveRecord::Base
belongs_to :person
end
This tells ActiveRecord that the Person model can accept attributes for Address, and will pass along the attributes to the correct model to be created.
<% form_for :person do |p| %>
<% p.fields_for :address do |a| %>
use the a form builder to create
fields for the address model here
<% end %>
<% end %>
chaining the fields_for
helper from the p
form builder lets the helpers generate attributes in the correct format.
More information: Nested Model Forms
Pretty much the same way as before except you'll need to build the params. You can look at your log to see how params are being sent.
eg.
def create
@silly_hat = SillyHat.new( :name => params[:name], :size => params[:size], :colour => params[:colour] )
if @silly_hat.save
...
精彩评论