所以我必須遵循以下模型。Rails協會 - 強大的參數構建
class Team < ActiveRecord::Base
belongs_to :user
has_and_belongs_to_many :players
accepts_nested_attributes_for :players
end
class Player < ActiveRecord::Base
has_many :statistics
has_and_belongs_to_many :teams
end
我希望建立一個有玩家的團隊,這些將由用戶選擇。我可以在控制檯中完成以下操作。
@user = User.find(10)
@team = @user.build_team(name: "MyTeam", points: 0)
#<Team team_id: nil, name: "MyTeam", points: 0, user_id: 10>
@team.players.build(name: "Messi")
#<Player player_id: nil, name: "Messi", role: nil>
@team.save
但是,我真的很掙扎傳遞參數,由於強參數。這是我的看法
<%= form_for :team do |f| %>
<%= f.label :name %><br />
<%= f.text_field :name %>
<%= f.fields_for :players do |players| %>
<%= players.label :player_name %>
<%= players.text_field :name %>
<% end %>
<div><%= f.submit "Create Team" %></div>
<% end %>
我想建立使用球隊的參數和使用播放器參數的球員的球隊,但我無法弄清楚如何在控制器得到這個工作。
class TeamController < ApplicationController
before_action :authenticate_user!
def new
end
def create
@user = User.find(current_user.id)
@team = @user.build_team(team_params) #Just the team paramaters
@team = @team.players.build(player_params)# I want just the player params
@team.save
end
private
# I can add the player param as nested i.e. .permit(:name, :players => [:name])
# but then build_team complains about receiving an array.
def team_params
params.require(:team).permit(:name)
end
end
任何解決方案,歡迎,以及任何改進。
編輯 - 添加的架構
create_table "players", primary_key: "player_id", force: true do |t|
t.string "name", limit: 50, null: false
t.string "role", limit: 30, null: false
end
create_table "players_teams", id: false, force: true do |t|
t.integer "player_id", null: false
t.integer "team_id", null: false
end
# players_teams is a Composite Primary Key, as instructed in the guides;
# also essential for targeting.
create_table "teams", primary_key: "team_id", force: true do |t|
t.string "name", limit: 200, null: false
t.integer "points", default: 0, null: false
t.integer "user_id", null: false
end
EDIT 2
由於這還沒有得到答覆,我會添加更多的解釋,我所嘗試。
用戶有一個團隊,我可以建立團隊,並且由於ActiveRecord的關係也建立了。用戶團隊有很多玩家,玩家有很多團隊,當我嘗試建立這種關係時,玩家表永遠不會改變,不會創建任何關係。
我覺得我應該再次強調的是,以下的作品完美地在鐵軌控制檯
@user = User.find(10)
@team = @user.build_team(name: "MyTeam", points: 0)
#<Team team_id: nil, name: "MyTeam", points: 0, user_id: 10>
@team.players.build(name: "Messi")
#<Player player_id: nil, name: "Messi", role: nil>
@team.save
隊被設置爲接受嵌套的參數,所以我認爲這是可行的。
@team = @user.build_team(team_params)
def team_params
params.require(:team).permit(:name, players_attributes: [:name, :role])
end
我相信這應該建立玩家模型並創建關係,但是沒有玩家插入並且沒有建立關係。
你能從'schema.rb'分享teams'和'players'表的'模式。將其添加到問題中。 –
我已經添加了。 –