【发布时间】:2018-03-04 17:23:09
【问题描述】:
我尝试以一种可以从已注册玩家列表中选择玩家的形式在比赛和 2 名玩家之间建立联系:
<%= f.label :"Joueur 1" %>
<%= f.select :playerone, @players.collect {|a| [a.name, a.id]} , class: 'form-control' %>
<%= f.label :"Joueur 2" %>
<%= f.select :playertwo, @players.collect {|b| [b.name, b.id]} , class: 'form-control' %>
<%= f.label :Prolongations %>
<%= f.check_box :prolongations %><br />
<%= f.submit yield(:button_text), class: "btn btn-primary" %>
表的架构:加入表匹配玩家
create_table "matches", force: :cascade do |t|
t.boolean "prolongations"
end
create_table "matches_players", id: false, force: :cascade do |t|
t.integer "match_id", null: false
t.integer "player_id", null: false
t.index ["match_id", "player_id"], name: "index_matches_players_on_match_id_and_player_id"
t.index ["player_id", "match_id"], name: "index_matches_players_on_player_id_and_match_id"
end
create_table "players", force: :cascade do |t|
t.string "name"
t.integer "points"
end
在matches.controller中:
class MatchesController < ApplicationController
attr_accessor :player_id, :playerone, :playertwo
def new
@match= Match.new
@players = Player.all
end
def create
@match = Match.new(match_params)
@players = Player.all
if @match.save
flash[:success] = "Votre match a bien été enregistré !"
redirect_to @match
else
render 'new'
p "Une erreur existe, veuillez recommencer."
end
end
def show
@match = Match.find(params[:id])
end
private
def match_params
params.require(:match).permit(:prolongations, :playerone, :playertwo)
end
end
在 Match 模型中:
class Match < ApplicationRecord
has_many :teams , class_name: "Team"
belongs_to :playerone, class_name: "Player" ,foreign_key: "player_id"
belongs_to :playertwo, class_name: "Player" ,foreign_key: "player_id"
end
我提交表单时的结果是:
Player(#69852298534200) 预期,得到“1”,它是 String(#4817000) 的一个实例
{"utf8"=>"✓",
"authenticity_token"=>".............",
"match"=>{"playerone"=>"1", "playertwo"=>"3", "prolongations"=>"0"},
"commit"=>"Enregistrer le match"}
我该如何解决?
【问题讨论】:
标签: ruby-on-rails forms select