当我尝试更新我的页面对象时,我收到错误“未定义的方法`update_attributes'为nil:NilClass”。我在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]
答案 0 :(得分:1)
确保params[:id]
不是空白,您可以查看您的观看次数。然后您可以使用ID搜索,如果没有记录,则使用Object
' s #try
方法:
@page = Page.find_by_id(params[:id])
if @page.try(:update_attributes, page_params)
...