【发布时间】: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:inpage_params' app/controllers/pages_controller.rb:39:inupdate'我猜它抛出了这个错误,因为我正在使用 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