Posted by
flyerhzm
on
October 03, 2010
Do you always check if ActiveRecord's attributes exist or not by nil?, blank? or present? ? Don't do that again, rails provides a cleaner way by query attribute
Bad Smell
<% if @user.login.blank? %>
<%= link_to 'login', new_session_path %>
<% end %>
<% if @user.login.present? %>
<%= @user.login %>
<% end %>
It's not bad, but rails provides a cleaner way, we should use query attributes to make codes simpler
Refactor
<% unless @user.login? %>
<%= link_to 'login', new_session_path %>
<% end %>
<% if @user.login? %>
<%= @user.login %>
<% end %>
As you seen, the query attribute is almost the same as the present? method call on attribute, or the opposite of blank? method call. Each attribute of ActiveRecord's model has a query method, so you don't need to use the present? or blank? for ActiveRecord's attributes.

Comments
I just tried and for non-existing attributes, is it intended that it throws a no method error?
Say my Project model doesn't have the due_at field,
Project.first.due_at?
#=>NoMethodError
Also, you can not call the not-existing due_at attribute itself, so i think there's no drawback.
If you read the source codes of ActiveRecord, you will see that number field is the only exception, be careful.
Say in devise, it uses password and password_confrimation accessors
And in my code `if user_account.password.blank?`, why the gem still barks at me?
or (shorter but more obscure) :
It seems clearer to me, even if in a real world use case I'd put the logic in a helper.
<%= @user.login %>
<% end %>
refactoring
<%= @user.login if @user.login? %>
Refactoring:
to
And it won't query twice, AR will cache the object in memory.