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:
"Called id for nil, which would mistakenly be 4 -- if you really wanted the id of nil, use object_id"
Is the standard message in Rails that tells you that you tried to invoke .id
on a nil
value.
So if @subject
is 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 @subject
may be nil
and address it in how you present the information. Look at the code and think what you should be presenting in the view there if @subject
is nil
.
Not having seen the code you're working with I may be wrong. But should you be using
params[:id]
For a quick check, just put this before the if statement:
puts ">>> #{params[:subject_id]}"
If it gives you the ID, I'm wrong...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With