2013-07-26 59 views
0

我正在創建第一個rails應用程序,並且昨天一切正常。我今天創建了關於我的觀點的關聯,讓玩家可以通過has_many和belongs_to進入團隊頁面。現在我無法創建一個新玩家,因爲它一直在PlayerController#create message中給我一個ActiveModel :: ForbiddenAttributesError。PlayersController中的ActiveModel :: ForbiddenAttributesError#create

提取的源(左右線#27):

def create 
    @player = Player.create(params[:player]) 
    respond_to do |format| 
     if @player.save 

參數:

{"utf8"=>"✓", 
"authenticity_token"=>"uw5w2sOgNF6y3+Jv6kvTj3X/dV2+PAVo2/OyHinIirY=", 
"player"=>{"first_name"=>"test", 
"last_name"=>"", 
"address_1"=>"", 
"address_2"=>"", 
"city"=>"", 
"state"=>"", 
"zip"=>"", 
"phone_number"=>"", 
"email"=>"", 
"birthday"=>"", 
"position"=>"", 
"bio"=>"", 
"team"=>"", 
"team_id"=>"1", 
"number"=>""}, 
"commit"=>"Create Player"} 

我的球員控制器創建是:

高清創建 @player = Player.new( player_params)

respond_to do |format| 
    if @player.save 
    format.html { redirect_to @player, notice: 'Player was successfully created.' } 
    format.json { render action: 'show', status: :created, location: @player } 
    else 
    format.html { render action: 'new' } 
    format.json { render json: @player.errors, status: :unprocessable_entity } 
    end 
end 

+0

嗨本傑明...謝謝你的迴應。這似乎並沒有這樣做。我已經將player_params設置爲params.require。 –

+0

看到我的回答波紋管 – Benj

回答

2

你應該在你的控制器此player_params方法,並用它來PARAMS傳遞給你的模型操作(創建,更新)

class PlayersController 
    ... 
    def create 
    @player = Player.create(player_params) 
    ... 
    end 

    private 

    def player_params 
    allow = [:first_name, :last_name, :address_1, :address_2, :city, :state, :zip, :phone_number, :email, :birthday, :position, :bio, :team, :team_id, :number] 
    params.require(:player).permit(allow) 
    end 
end 
+0

謝謝你本傑明......一個人做到了。 –

0
class PlayersController 

    ... 

def create 
    @player = Player.new(player_params) 

    ... 

    end 

private 

def player_params 

    params.require(:player).permit(:first_name, :last_name, :address_1, :address_2, :city, :state, :zip, :phone_number, :email, :birthday, :position, :bio, :team, :team_id, :number) 

    end 

end 
+1

因此......這與其他答案基本上是100%相同,只是空白行更多? –

1

我已經去瘋狂尋找解決方案,當我已經應用了params.require位。因此,對於誰使用康康舞人,你需要將此部分添加到ApplicationController中:

參見:https://github.com/ryanb/cancan/issues/571

before_filter do 
    resource = controller_name.singularize.to_sym 
    method = "#{resource}_params" 
    params[resource] &&= send(method) if respond_to?(method, true) 
end 
0

如果您使用的Rails 4,你已經添加player_params方法,不要忘了在創建方法中將params[:player]更改爲player_params

相關問題