Simple Problem (and Solution) with ActiveRecord Relations
I had a simple beginner’s problem with using a scope to find records in my db:
@sub = Sub.where(:id => :sub_id)
It would pull the correct records fine, but when I’d want to access that info through helpers like
@sub.name, it would throw and undefined method ‘name’ error. The problem is very simple though. Since a scope isn’t guaranteed to be one record, you either have to use a block:
@sub.each do |sub| ... end
Or, use something more definitive, like the
@sub = Sub.where(:id => :sub_id).find(:first)
Even though I know the first example should return only one record, it’s not certain. If you look at the class of the returned object from a scope, it says ActiveRecord::Relation whereas records returned with the find method will have the class of the model that called them.
It seems simple, but it took me the longest time to find this bit of information, so here you go.