Search code examples
ruby-on-railsformscustom-routes

custom action submitting multiple forms in Rails


So I have this structure of application: a Game model which has many Allies and many Enemies.

I want to create a custom action for Game dedicated to create and submit enemies and allies. So in the view I will have 2 fields_for that you can submit at the same time.

I have never created custom routes and actions or submitted 2 children forms in the same page.

Anyone know how I could do this ? Thanks


Solution

  • routes.rb

    #this route shows the form
    get 'create-players/:id', to 'game#new_players', as: :new_players
    # this route recieves the form post submission
    post 'create-players/:id', to 'game#create_players', as: :create_players
    

    app/controllers/game_controller.rb:

    def new_players
      @game = Game.find(params[:id])
    end
    
    def create_players
      #do whatever you want with the params passed from the form like
      @allies = Ally.create(game_id: params[:id], name: params[:ally_fields][:name])
      @enemies = Enemy.create(game_id: params[:id], name: params[:enemy_fields][:name])
      @game = Game.find(params[:id])
    end
    

    app/views/game/new_players.html.erb:

    <%= form_tag(create_players_paths, @game.id), method: 'POST') do %>
      <% #...fields you have on models, perhaps %>
      <% fields_for :ally_fields do |f|
        <%= f.text_field :name, nil, placeholder: "Ally name", required: true
      <% end % >
      <% fields_for :enemy_fields do |f|
        <%= f.text_field :name, nil, placeholder: "Enemy name", required: true
      <% end % >
      <%= submit_tag "create players", class: "submit" %>
    <% end %>
    

    app/views/game/create_players.html.erb:

       <h1> Woah an allie and an enemy have been added to game <%= @game.id %></h1>
       <p> Lets see some blood!</p>
    

    Of course, you should enforce verifications on the input and before processing the post submission. Usually you'll want to use established relationships between objects, so that you can do on the view @model = Modelname.new then, form_for @object and have validations and error messages accessible in a much cleaner way.