3 ms·
The child objects may not exist. "u" is nil (a null pointer, more or less), calling "u.profiles" sends the :profiles message to nil. NilClass probably doesn't h
by pdkl95 11y ago
The child objects may not exist. "u" is nil (a null pointer, more or less), calling "u.profiles" sends the :profiles message to nil. NilClass probably doesn't have a :profiles method, so this will probably raise a NoMethodError exception.
As for why this is a common problem, "u.profiles.thumbnails.large" is is probably a chain of Rails/ActiveRecord model associations[1], which generally map to table rows . If there the "profiles" table doesn't have any rows "WHERE profiles.user_id = users.id", then ActiveRecord will leave a nil[2] (or empty array) in user.profiles. This is true for all foreign key relationships, so you often end up having to do something to protect against null values (no rows) every time you move between models.
Sometimes it is possible to work around this by always creating the associated model when the parent object is created, that only works in a few cases. Note: I recommend against doing tricks to auto-build the associated model on first access: that kind of "clever" solution can lead to confusing bugs later on. (I learned that one the hard way)
[1] http://guides.rubyonrails.org/association_basics.html http://guides.rubyonrails.org/association_basics.html
[2] ibid, 4.1.1.1 "The association method returns the associated object, if any. If no associated object is found, it returns nil."
- gotchange 11y agoThanks for the detailed answer. I think it's safe to assume that Ruby is a bit complicated at least for me but my main point was if he is just interested in checking for the `large` prop (I am not sure about the proper term here in Ruby), I'd expect him to just check for it directly and if this fails, he goes on to the next step as planned and that's why it seemed bit redundant to me esp. I didn't see any exceptions handling done to make use of the fail of previous checks on that chain to instruct the end user or dev accordingly. Again excuse my ignorance of the subject and technical details in Ruby.