0

我正在创建第一个 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 create @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

结尾

4

4 回答 4

2

您应该player_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
于 2013-07-26T05:33:28.293 回答
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
于 2014-05-26T22:39:26.667 回答
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
于 2014-01-10T15:21:54.593 回答
0

如果您使用的是 Rails 4 并且添加了player_params方法,请不要忘记将params[:player]create 方法更改为player_params.

于 2016-04-06T14:29:48.007 回答