Search code examples
ruby-on-railsformshttpstrong-parameters

Submit same form to different actions


Depending on which submit button a user selects, (Cat and Dog in this case), I'd like to submit the form to the right controller action using the right http verb.

In this case, there is one text input. If the user presses Cat I'd like to POST to Cats#create and if Dog to PUT to Dogs#update.

How would I build the form?

enter image description here

Edit

Using the formaction attribute I'm able to PUT to Dogs#update

<%= form_for(cat) do |f| %>

  <div class="field">
    <%= f.label :name %>
    <%= f.text_field :name %>
  </div>


  <div class="actions">
    <%= f.submit "Cat" %>
    <%= f.submit "Dog", formaction: dog_path(Dog.first) %>
    <%#= f.submit "Cat", name: 'route_to[cat]' %>
    <%#= f.submit "Dog", name: 'route_to[dog]' %>
  </div>
<% end %>

The problem is I want to POST to Dogs#create, is this possible with formaction?

Edit

There is a railscast about building the logic the controller based on the name of the button pressed. But I want to put the logic about which HTTP verb, controller, and action in the submit button itself. Is this possible?


Solution

  • In this case creating a Cat and updating a Dog were related enough that it makes sense to handle both in the CatsController with a case statement and use a :name attribute on on the submit button.

    For example:

    app/views/cats/new.html.erb:

    <%= form_tag(cats_path, multipart: true, role: "form") do %>
      <%= button_tag 'Cat', name: 'route_to[cat]'%>
      <%= button_tag 'Dog', name: 'route_to[dog]' %>
    <% end %>
    

    app/controllers/cats_controller.rb:

    def create
      case route_to params
      when :cat
        # create a cat
      when :dog
        # update a dog
      end
    end
    .
    .
    .
    private
    
      def route_to params
        params[:route_to].keys.first.to_sym
      end