Tuesday, July 8, 2014

Rails try method name in object

In rails, most cases we are using the following style of code to display name, text etc..
user && user.name
It will go lengthier & is hard to maintain, check the below one
user && !user.comments.blank? && user.comments.first.text
Avoid lengthy expressions, start using "try"
user.try(:name)
It will return user name only if user object exists. Happy coding..

No comments:

Post a Comment