我正在创建第一个rails应用程序并且昨天一切正常。我今天在视图上创建了关联,玩家可以使用has_many和belongs_to进入团队页面。现在我无法创建一个新的播放器,因为它在PlayersController #create消息中不断给我一个ActiveModel :: ForbiddenAttributesError。
提取的来源(第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"}
我的玩家控制器是:
def创建 @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 :(得分: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
答案 1 :(得分:1)
当我已经应用了params.require位时,我一直在寻找解决方案。因此,对于使用 cancan 的用户,您需要将此部分添加到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
答案 2 :(得分: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
答案 3 :(得分:0)
如果您使用的是Rails 4并且添加了player_params
方法,请不要忘记将创建方法中的params[:player]
更改为player_params
。