我有用户,游戏和玩家模型,在我的游戏节目页面中,我正在尝试创建一个与当前用户和游戏相关联的玩家。
所以我在页面blah.com/game/1
(显示身份1的游戏页面)并想按一个按钮来创建一个玩家。
在我的游戏展示页面中:
# I have @game here which is a reference to the game for this page
# can I use it here to fill in @player.game ?
<%= form_for(@player) do |f| %>
<%= f.submit "Create player for this game (join this game)" %>
<% end %>
然后,在我的PlayerController的create方法中:
# PlayerController's create, called from Game's show page
def create
@terra_player = current_user.players.build() # approximation of how it works
if @terra_player.save
redirect_to @terra_player
else
render 'new'
end
end
我相信我需要手动填写游戏的参数,但我不确定如何获得我所拥有的游戏的参考。我想我需要在创建控制器中填写参数:
@terra_player = current_user.players.build(:game => ???) # approximation of how it works
或者在显示页面中设置它。但在任何一种情况下,我都不确定。
答案 0 :(得分:3)
你的模型在这里有点棘手;我会说你需要清理你的语义。只是在这里采取刺,但我的猜测是,更好的选择接近这一点,认为玩家与游戏的关系比用户更紧密。您的模型应该看起来像这样:
class User < ActiveRecord::Base
has_many :players
has_many :games, :through => :players
end
class Game < ActiveRecord::Base
has_many :players
validate :max_players_in_game #left as exercise to reader
end
class Player < ActiveRecord::Base
belongs_to :user
belongs_to :game
end
然后在您的路线中,您将拥有游戏的嵌套资源:
resources :games do
resources :players
end
所以你的网址看起来像这样:POST /games/1/players
。在你的PlayersController中:
class PlayersController < ApplicationController
def create
@game = Game.find(params[:game_id])
@player = @game.players.build(:user => current_user)
if @player.save
redirect_to @game
else
render "new"
end
end
end
答案 1 :(得分:0)
令人毛骨悚然的方式是
MyController.new.create_method parameters
我建议不要这样做。 : - )