【问题标题】:undefined method `update_attributes' for nil:NilClass when updating object更新对象时为 nil:NilClass 定义的未定义方法“update_attributes”
【发布时间】:2017-03-17 12:20:21
【问题描述】:

当我尝试更新我的页面对象时,我收到错误“nil:NilClass 的未定义方法 `update_attributes'”。我在 pry 中确认 @page 是空的,但我不知道为什么?

def new
    @page = Page.new
    @subjects = Subject.order('position ASC')
    @page_count = Page.count + 1
  end

  def create
    @page = Page.new(page_params)
    if @page.save
      flash[:notice] = 'New page added!'
      redirect_to action: 'index'
    else
      @subjects = Subject.order('position ASC')
      @page_count = Page.count + 1
      render 'new'
    end
  end

  def edit
    @page = Page.find_by(id: params[:id])
    @subjects = Subject.order('position ASC')
    @page_count = Page.count
  end

  def update
    @page = Page.find_by(id: params[:id])
    if @page.update_attributes(page_params)
      flash[:notice] = 'Page has been updated!'
      redirect_to action: 'show', id: @page.id
    else
      @subjects = Subject.order('position ASC')
      @page_count = Page.count
      render 'edit'
    end
  end
     private

  def page_params
    params.require(:page).permit(:subject_id, :name, :permalink, :position, :visible)
  end

Routes:
match ':controller(/:action(/:id))', :via => [:get, :post]

【问题讨论】:

  • 在你的控制台中检查Page.find_by(id: params[:id])的输出。
  • 控制台显示此错误:ActionController::ParameterMissing (param is missing or the value is empty: page): app/controllers/pages_controller.rb:62:in page_params' app/controllers/pages_controller.rb:39:in update' 我猜它抛出了这个错误,因为我正在使用 params.require( :page) 具有我强大的参数,但没有对象通过?抱歉,我对 Rails 还很陌生。
  • ok.. 然后在控制台中检查 puts params... 或在浏览器 network 选项卡中。
  • 没有“id”通过...=> {"utf8"=>"✓", "authenticity_token"=>"eZy9jQd9MYterxH43Pkfquh91dk/qux0dCB7c6apE2c=", "page"=> {"subject_id"=>"24", "name"=>"Testing Page", "permalink"=>"0", "position"=>"1", "visible"=>"1"}, "commit"=>"Update page", "controller"=>"pages", "action"=>"update"}
  • 我在你的参数哈希中看不到任何:id

标签: ruby-on-rails ruby ruby-on-rails-4


【解决方案1】:

确保params[:id] 不为空,您可以查看您的视图。然后就可以使用id搜索了,没有记录的情况下使用Object#try方法:

@page = Page.find_by_id(params[:id])
if @page.try(:update_attributes, page_params)
...

【讨论】:

  • 问题是在调用“create”操作时 params[:id] 为空。但是,在“新”操作中 params[:id] 存在。我很困惑为什么会这样。我尝试了您的代码,但收到一个新错误:undefined method name' for nil:NilClass` 我想这基本上是在告诉我同样的事情 - params[:id] 是空白的。由于我是 Rails 的新手,因此我提前道歉。
  • @user3403328 验证您的观点,如果新操作包含 id,但它不是外壳。在帖子中显示您的新/显示视图
  • 哇,你说得对。问题在我看来。我的上帝,宝贵的教训是我需要在任何地方仔细检查。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-27
相关资源
最近更新 更多