【问题标题】:custom action submitting multiple forms in Rails在 Rails 中提交多个表单的自定义操作
【发布时间】:2017-07-19 10:44:23
【问题描述】:

所以我有这样的应用程序结构:一个Game 模型,它有很多Allies 和很多Enemies

我想为Game 创建一个自定义动作,专门用于创建和提交敌人和盟友。 所以在视图中我会有 2 个 fields_for,你可以同时提交。

我从未创建过自定义路由和操作,也从未在同一页面中提交过 2 个子表单。

有谁知道我该怎么做?谢谢

【问题讨论】:

  • 你有Player 型号吗?如果是这样,GamePlayer 之间的关联是什么
  • 我没有播放器模型。游戏 has_many :allies 和 has_many: 敌人。

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


【解决方案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

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>

当然,您应该在处理提交提交之前对输入进行验证。通常您会希望使用对象之间已建立的关系,以便您可以在视图@model = Modelname.new 然后form_for @object 上执行操作,并以更简洁的方式访问验证和错误消息。

【讨论】:

  • 必须将 post 'create-players/:id', to 'game#create_players', as: :create_players 更改为 get 'create-players/:id', to: 'games#create_players', as: :create_players 才能使其正常工作,但提交按钮现在不起作用
  • 我需要 2 条路线吗?
  • @LRP 写了更多解释
  • 非常感谢,这正是我想要的
猜你喜欢
  • 2021-01-11
  • 1970-01-01
  • 2013-08-19
  • 1970-01-01
  • 1970-01-01
  • 2022-11-22
  • 1970-01-01
  • 2013-11-06
  • 1970-01-01
相关资源
最近更新 更多