How to initiate various actions based on the submit button in rails

I have a form with a list of things and an action that already exists to update elements.

I want to have another button that, when clicked, triggers triggers to delete selected items.

= form_for @new_item,:url => {:controller => "item_lists",:action => "update_list" } do |f| - @items.each do |it| %input{:type=>"hidden",:name=>"item_list[#{it.id}]position",:value=>it.position, :class=>'position'} %textarea{:name=>"item_list[#{it.id}]field1"} =it.field1 %textarea{:name=>"item_list[#{it.id}]field2"} =it.field2 %input{:type=>'checkbox', :name=>'selected_items[]', :value=>it.id} =(it.valid?) ? "" : it.errors.full_messages %input{:type=>"submit", :value=>"Save changes", :name=>'save'} %input{:type=>"submit", :value=>"Remove selected", :name=>'delete'} 

This question seems to indicate that I should check the parameters in my action to find out what was clicked. But it seems messy, my controller can quickly degenerate into a bunch of ifs when I add more actions.

Is there a more elegant way to do this, i.e. make it just go to the correct method?

Thanks for any help ...

+4
source share
2 answers

This is not a gel with REST. In REST and Rails, you will usually have one action on the endpoint, rather than a decision on the endpoint based on some query criteria.

At the same time, you can filter actions based on the submit button by checking the name of the pressed button. See this SO question .

I would say that this only works if your form does slightly different things, for example, the submit button, which is updated compared to the submit button, which redirects somewhere later, for example. “Refresh” versus “Refresh and continue” (far-fetched, but you understand what I mean).


Addressing your issue in the comments, your method should not go into a long if s sequence. You can simply write code to determine which method to call based on the name of the submit button. A simple implementation could be:

 # your form action def update_list send update_list_action end protected def update_list_action # just return the first action name found in the params action = %w(save delete).detect {|action| params[action] } "update_list_#{action}" end def update_list_save # handle save end def update_list_delete # handle delete end 
+3
source

I would suggest you add a drop-down menu with the option to "delete", "update", ... and add jQuery code that tracks the selected item and changes the action your form depending on the value, because you should not use one action to update and delete objects! There must be one action to update and one to delete!

0
source

Source: https://habr.com/ru/post/1382918/


All Articles