【问题标题】:ActiveModel::ForbiddenAttributesError in PlayersController#createPlayersController#create 中的 ActiveModel::ForbiddenAttributesError
【发布时间】:2013-07-26 04:01:40
【问题描述】:

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

我用于创建的玩家控制器是:

定义创建 @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

结束

【问题讨论】:

  • 您好本杰明...谢谢您的回复。那似乎没有做到。我已经将 player_params 设置为 params.require。

标签: ruby-on-rails


【解决方案1】:

你应该在你的控制器中有这个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

【讨论】:

  • 谢谢本杰明……那人做到了。
【解决方案2】:

当我已经应用了 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

【讨论】:

    【解决方案3】:
    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
    

    【讨论】:

    • 所以...这基本上与其他答案 100% 相同,只是有更多的空行?
    【解决方案4】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-20
      • 2013-11-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多