gpt4 book ai didi

ruby-on-rails - 精彩的 ActiveModel::ForbiddenAttributesError

转载 作者:行者123 更新时间:2023-12-03 16:14:26 24 4
gpt4 key购买 nike

我一直在使用 strong_params 并试图让创建的对象通过。我有两个问题。

  • 您如何找出导致问题的属性?
  • 我在下面的代码中缺少什么?

  • 让我们从错误开始,日志什么也没告诉我。
    ActiveModel::ForbiddenAttributesError in JobsController#create

    只是为了傻笑,这是我认为不是很有用的日志:
    Started POST "/jobs" for 127.0.0.1 at 2013-12-17 22:03:59 +0000
    Processing by JobsController#create as HTML
    Parameters: {"utf8"=>"✓", "authenticity_token"=>"Ohq4lVqPVMpjzbZwCfJNYBL78TAcoC0WZLSmpCzMD3k=", "job"=>{"job_title"=>"Junior Rails Developer", "job_description"=>"A new position getig nsomethfins lansnana", "languages"=>["", "Rails", "Ruby"], "country_code"=>"AO", "job_type"=>"Full-Time", "job_salary"=>"30000", "job_level"=>"Junior"}, "commit"=>"Create Job"}
    User Load (0.5ms) SELECT "users".* FROM "users" WHERE "users"."id" = 1 ORDER BY "users"."id" ASC LIMIT 1
    Completed 500 Internal Server Error in 8ms

    ActiveModel::ForbiddenAttributesError (ActiveModel::ForbiddenAttributesError):

    有道理,但如果我看看我的创造:
    def create
    binding.pry
    @job = Job.new(job_params)

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

    强参数:
     def job_params
    params.require(:job).permit(:job_title, :job_level, :job_description, :job_salary,
    :country_code, :job_type, :state, :languages => [])
    end

    我主要感兴趣的是如何找出 future 的问题所在,因为它似乎是大海捞针错误。

    最佳答案

    在您的日志文件中,它显示了应用程序从创建中获取的参数:

    Parameters: {"utf8"=>"✓", "authenticity_token"=>"Ohq4lVqPVMpjzbZwCfJNYBL78TAcoC0WZLSmpCzMD3k=", "job"=>{"job_title"=>"Junior Rails Developer", "job_description"=>"A new position getig nsomethfins lansnana", "languages"=>["", "Rails", "Ruby"], "country_code"=>"AO", "job_type"=>"Full-Time", "job_salary"=>"30000", "job_level"=>"Junior"}, "commit"=>"Create Job"}

    您需要首先确保每个参数都列在您的强参数定义中。然后确保每个参数都是正确的类型。
    :parameter          #accepts a single entry
    :parameter => [] #accepts a hash
    :paramters_attributes: [:firstattribute, :secondattribute] #accepts nested parameters

    您的语言参数在日志中显示为散列,但您的允许参数中只有 :languages。更改参数以接受散列应该可以解决问题。
    :languages => []

    此外,此博客文章通过示例显示一些强大的参数很有帮助:
    http://blog.sensible.io/2013/08/17/strong-parameters-by-example.html

    关于ruby-on-rails - 精彩的 ActiveModel::ForbiddenAttributesError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20645830/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com