Multiple submit buttons/forms in Rails

2019-02-09 01:07发布

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?

2条回答
forever°为你锁心
2楼-- · 2019-02-09 01:23

Make each row in the list a form and put the info about the item in question there. Of course, you'll need to submit and reload the page with each action. The only way around this is to use checkboxes instead of buttons and make it one big form — or to use Javascript.

As for your second question, if you want to have a submit button affect two "forms," you should make them both part of the same form. You can have multiple submit buttons on the form if you need to. Otherwise, you could dynamically generate a third form with Javascript filled with the values from the original form — but that wouldn't work in all cases (e.g., file inputs).

查看更多
冷血范
3楼-- · 2019-02-09 01:27

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

查看更多
登录 后发表回答