自定义操作在Rails中提交多个表单

时间:2017-07-19 10:44:23

标签: ruby-on-rails forms custom-routes

所以我有这种应用程序结构:Game模型,其中包含许多Allies和许多Enemies

我想为Game创建一个专门用于创建和提交敌人和盟友的自定义操作。 因此,在视图中,我将有2个fields_for,您可以同时提交。

我从未在同一页面中创建自定义路线和操作或提交了2个子窗体。

任何人都知道如何做到这一点?感谢

1 个答案:

答案 0 :(得分:1)

<强>的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

应用程序/控制器/ 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

应用程序/视图/游戏/ 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 %>

应用程序/视图/游戏/ 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>

当然,您应该对输入进行验证,然后再处理帖子提交。通常,您需要使用对象之间建立的关系,以便您可以在视图@model = Modelname.new上执行form_for @object,并以更清晰的方式访问验证和错误消息。