user3403328
user3403328

Reputation: 115

undefined method `update_attributes' for nil:NilClass when updating object

I'm receiving the error "undefined method `update_attributes' for nil:NilClass" when I try to update my page object. I confirmed in pry that @page is empty, but I can't figure out why?

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]

Upvotes: 0

Views: 1983

Answers (1)

Малъ Скрылевъ
Малъ Скрылевъ

Reputation: 16507

Make sure that params[:id] isn't blank, you can check your views for it. Then you can use search by id, and in case of no record use Object's #try method:

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

Upvotes: 1

Related Questions