I’m following the Kevin Skoglund tutorial Ruby on Rails 3 Essential Training, which was written for rails 3.0, though I am currently using 3.2. It uses the following method in the pages_controller with a before_filter to display only the pages which belong to the parent subject.
The tutorial explicitly uses .find_by_id because if the result is nil it “will not return an error”. However I get the “Called id for nil, which would mistakenly be 4 — if you really wanted the id of nil, use object_id” error when trying to view a page where @subject has been set to nil.
def find_subject
if params[:subject_id]
@subject = Subject.find_by_id(params[:subject_id])
end
end
The actual code that is causing the error is:
def list
@pages = Page.order("pages.position ASC").where(:subject_id => @subject.id)
end
Is this something that has changed since 3.0? If so, what would be the correct way to implement this functionality in 3.2?
The message:
Is the standard message in Rails that tells you that you tried to invoke
.idon anilvalue.So if
@subjectis nil, then it’s normal, appropriate behavior to get that message if you try to call@subject.id.I’d recommend that in the view file you take into account that
@subjectmay beniland address it in how you present the information. Look at the code and think what you should be presenting in the view there if@subjectisnil.