Ruby-on-rails – Multiple submit buttons/forms in Rails

formsrubyruby-on-railssubmit

I am trying to write a rails application which lets you go to a certain page, say /person/:id. On this page it shows a set of available resources. I want each resource to have a button next to it, which reserves that resource to that person (by creating a new instance of an Allocation model.) As an extension, I'd like several buttons by each resource, that cancel reservations and do other things. I'd also like to input data alongside some of the buttons, e.g. to allocate some % of a resource.

My problem is I can't work out how to sensibly do this without repeating myself, or having a very hacky controller. How can I do this without matching on the value part of the submit buttons (the text on the buttons), or using any javascript?

Additionally, if you have two forms on a page, how do you set it up so changes on both forms are saved when any submit button is clicked?

Best Answer

im using jQuery, and this is what i did :

<script type="text/javascript">
    $(document).ready(function() {

        $('#bulk_print').click(function(){
            var target = '<%= bulk_print_prepaid_vouchers_path(:format => :pdf) %>';
            $('#prepaidvoucher_bulk_print').attr('action', target);
            $('#prepaidvoucher_bulk_print').submit();
        });

        $('#bulk_destroy').click(function(){
            var target = '<%= bulk_destroy_prepaid_vouchers_path %>';
            $('#prepaidvoucher_bulk_print').attr('action', target);
            $('#prepaidvoucher_bulk_print').submit();
        });

    });
</script>

<% form_tag '#', :method => :post, :id => 'prepaidvoucher_bulk_print' do %>

your form details

<button class="button" type="submit" id="bulk_print">
   <%= image_tag("web-app-theme/printer.png", :alt => "Print Selected Vouchers") %> Print Selected Vouchers
</button>

<button class="button" type="submit" id="bulk_destroy">
    <%= image_tag("web-app-theme/cross.png", :alt => "Delete Selected Vouchers") %> Delete Selected Vouchers
</button>

<% end %>

The idea is to change the form action on the fly, based on which button is clicked