Hello, I have two forms in my rails app. They both exist in separate tabs and I when I submit one form I want the data in the other form to be saved as well. How should I do that? Or Is there a better way of doing this instead of using two separate forms? Is there a better way to spread a long form into multiple tabs and when I press submit all the data from all the tabs should reach my action. Thanks.
You can expand a single form to cover all elements of both forms.
This is perfectly ok, as long as the form tags fit validly into the X/HTML.
<form action='action1'>
<!-- All elements from both forms, plus tabs, etc. -->
</form>
The only thing to consider is if there will ever be another form inside that area that will need to go to another action. For example, if you add a third tab, in between the other two, that will have a different action.
You don't want to end up like:
<form action='action1'>
<!-- elements from the combined forms -->
<form action='action2'>
<!-- elements for a totally different form, not valid inside another form -->
</form>
<!-- more elements from the combined forms -->
</form>
In that case, it would be better to consolidate the two forms at submit time using JavaScript.
jQuery (jquery.com) would make this pretty easy. For example, you could serialize both forms, and then concatenate them and send the result to the server via post or get.
See http://docs.jquery.com/Ajax/serialize.
There might be better ways to do this, but I can't think of any off the top of my head.
I can't test if the concept work right now, but I believe that you could use jQuery to achieve that, its submit function will intercept all form submissions on any tab, something along these lines
$("form").submit(function(event){
event.preventDefault();
//serialize forms here and submit using jquery post
});
You should look into the fields_for method. You can do something like this:
<% form_for @house do |f| %>
<%= f.text_field :square_feet %>
<% fields_for @listing do |s| %>
<%= s.hidden_field :id %>
<%= s.text_field :asking_price %>
<% end %>
<%= f.submit %>
<% end %>
And then in your controller you'd do something like this:
house = House.find(params[:id])
house.update_attributes(params[:house])
listing = Listing.find(params[:listing][:id])
listing.update_attributes(params[:listing])
That's for an update, but you can do whatever you want in there.