使用Rails 3.1.0
def create
@practice = Practice.new(params[:practice])
respond_to do |format|
if (current_user.practices << @practice rescue false)
pmf = current_user.practices_users.inspect # if this line is removed the following update_attributes method breaks!
current_user.practices_users.last.update_attributes(:admin_flg => true, :first_name => params[:first_name], :last_name => params[:last_name])
format.html { redirect_to home_dashboard_path, notice: 'Practice was successfully created.' }
format.json { render json: @practice, status: :created, location: @practice }
else
format.html { render action: "new" }
format.json { render json: @practice.errors, status: :unprocessable_entity }
end
end
end
当'pmf = ...'行不存在时,我得到这一行
NoMethodError:
undefined method `update_attributes' for nil:NilClass
当'pmf = ...'行存在时,创建操作正常工作。发生了什么事?
答案 0 :(得分:2)
我不知道确切的答案,但我可以帮你调试......
当你这样做时
pmf = current_user.practices_users.inspect
然后Rails从数据库加载整个practices_users
(对于current_user),稍后稍后调用last
时,它会在对象上调用方法last
类型为Array
。
当你这样做时
current_user.practices_users.last
没有进行pmf调用,整个practices_users
集合还没有从数据库加载到数组中,Rails也不会加载整个集合,因为你想要的只是最后一个。当需要加载的所有项目都是最后一项时,加载项目数组将是一种浪费。因此它将生成仅从数据库加载单行的SQL。
在这种情况下,您需要查看控制台或开发日志,以确切了解SQL Rails生成的内容以及SQL未返回任何值的原因。然后就会清楚发生了什么。