我正在尝试创建一个同时创建游戏和游戏玩家的表单。 我遇到的问题是,当我提交表单时,会创建游戏,但游戏玩家不会。
我环顾四周,但没有找到任何有用的答案。
游戏模型
class Game < ActiveRecord::Base
belongs_to :league
has_many :game_players, :dependent => :destroy
accepts_nested_attributes_for :game_players
attr_accessible :league_id, :game_date
validate :league_id, :presence => true
end
Game_Player模型
class GamePlayer < ActiveRecord::Base
belongs_to :game
has_many :users
validate :game_id, :presence => true
validate :user_id, :presence => true
end
游戏控制器
class GamesController < ApplicationController
def new
@title = "New Game"
@game = Game.new
3.times { @game.game_players.build }
end
def create
@game = Game.new(:league_id => cookies[:league_id])
if @game.save
flash[:success] = "Succesfully Created Game"
redirect_to League.find_by_id(cookies[:league_id])
else
@title = "New Game"
render 'new'
end
end
表格
<%= form_for @game do |f| %>
<%= f.fields_for :game_players do |builder| %>
<p>
<%= builder.label :user_id, "User" %><br />
<%= builder.text_field :user_id %><br />
</p>
<% end %>
<p><%= f.submit "Submit" %></p>
<% end %>
答案 0 :(得分:0)
您很可能需要将:game_players_attributes
传递给attr_accessible
,因为.new尊重质量分配安全性