Count Method on Undefined Active Record Array @objects.count
Is there a way to write a clean if nil then in a view. Assuming my lack of ruby is biting me here. Example,
If object nil, then return开发者_Go百科, nothing found
have
<%= @objects.count if @objects %>
want something like this
<%= @objects.count if @objects then "nothing found" %>
There are many ways to write something like this.
Something simple would be:
<% if @objects %>
<%= @objects.count %>
<% else %>
nothing found
<% end %>
If you get into a slightly more complex conditional I would suggest moving the logic into a helper and call it from the view. ex:
<%= count_for(@object) %>
Here's a good solution for you:
<%= "nothing found" unless @objects.try(:length).to_i > 0 %>
One of the issues is that you can't run count
on a nil object. Therefore you need to use Rails' super handy .try()
method to return nil when @objects = nil
, rather than NoMethodError
.
Next issue: You can't make a comparison between nil
and a number using >
so you need to convert the results of @objects.length
to an integer which will return 0 for nil.
Lastly, try calling length
rather than count
. This will avoid running any extra queries when @objects
is defined.
Avoids: SELECT COUNT(*) FROM 'objects'
Also if you want to display the count using this one-liner technique you can simply write up a shorthand if/else statement as follows:
<%= @objects.try(:length).to_i > 0 ? @objects.length : "nothing found" %>
One last option:
Use the pluralize method, which can handle a nil count:
Showing <%= pluralize( @objects.try(:length), 'object' ) %>
Sorry, I know this is pretty late, but hopefully helpful for someone else!
精彩评论