所以我有这种应用程序结构:Game
模型,其中包含许多Allies
和许多Enemies
。
我想为Game
创建一个专门用于创建和提交敌人和盟友的自定义操作。
因此,在视图中,我将有2个fields_for,您可以同时提交。
我从未在同一页面中创建自定义路线和操作或提交了2个子窗体。
任何人都知道如何做到这一点?感谢
答案 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
,并以更清晰的方式访问验证和错误消息。