在 Rails 中提交多个表单的自定义操作
custom action submitting multiple forms in Rails
所以我有这样的应用程序结构:一个 Game
模型,其中有许多 Allies
和许多 Enemies
。
我想为 Game
创建一个自定义操作,专门用于创建和提交敌人和盟友。
所以在视图中我将有 2 fields_for 你可以同时提交。
我从未在同一页面创建自定义路由和操作或提交 2 个子表单。
有人知道我该怎么做吗?谢谢
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>
当然,您应该在处理 post 提交之前对输入进行验证。通常您会希望使用对象之间已建立的关系,以便您可以在视图上执行 @model = Modelname.new
然后 form_for @object
并以更简洁的方式访问验证和错误消息。
所以我有这样的应用程序结构:一个 Game
模型,其中有许多 Allies
和许多 Enemies
。
我想为 Game
创建一个自定义操作,专门用于创建和提交敌人和盟友。
所以在视图中我将有 2 fields_for 你可以同时提交。
我从未在同一页面创建自定义路由和操作或提交 2 个子表单。
有人知道我该怎么做吗?谢谢
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>
当然,您应该在处理 post 提交之前对输入进行验证。通常您会希望使用对象之间已建立的关系,以便您可以在视图上执行 @model = Modelname.new
然后 form_for @object
并以更简洁的方式访问验证和错误消息。