【问题标题】:ActiveModel::ForbiddenAttributesError from model form.模型表单中的 ActiveModel::ForbiddenAttributesError。
【发布时间】:2015-03-24 07:14:08
【问题描述】:

我正在尝试创建一个表单来创建一个新的模型实例:

class Pokemon < ActiveRecord::Base
    belongs_to :trainer
    attr_accessor :name
end

在页面上:

<h1>Create a New Pokemon</h1>
<%= simple_form_for(@pokemon) do |f| %>
  <%= f.input :name  %>
  <%= f.button :submit %>
<% end %>

带控制器:

class PokemonsController < ApplicationController
  def new
    @pokemon = Pokemon.new
  end

  def create
    @pokemon = Pokemon.new(params[:pokemon]) #error stack comes from here
    @pokemon.trainer = current_trainer
    if @pokemon.save
      redirect_to trainer_path(current_trainer)
    end
  end

  private

  def pokemon_params
    params.require(:name).permit(:trainer)
  end
end

但我一直遇到以下错误:

ActiveModel::ForbiddenAttributesError

我尝试按照Active Model Forbidden attributes error 添加 params.require(...).permit(...) 但没有运气。关于什么可能是错误的任何见解?我对rails很陌生。

【问题讨论】:

    标签: ruby-on-rails


    【解决方案1】:

    试试这个:

    params.require(:pokemon).permit(:name)
    

    更改您的创建操作:

    def create
      ...
      @pokemon = Pokemon.new(pokemon_params)
      ...
    end
    

    【讨论】:

    • 没有得到同样的东西
    • 你试过这个@pokemon = Pokemon.new(pokemon_params) 吗?
    • 做到了!谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多