Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Better way to write @instances.count > 0

I have this code:

<% if  @states.count > 0 %>  # @states is an active record collection

I just feel like there should be a better way to write this.

I am looking for something like:

<% if  @states.not_empty? %>

I realize this is tiny change but it would be a welcome cleanup.

like image 654
Josh Avatar asked Oct 03 '12 19:10

Josh


3 Answers

You probably want ActiveRecord's any?

http://api.rubyonrails.org/classes/ActiveRecord/Relation.html#method-i-any-3F

<% if @states.any? %>
    Do stuff here if @states has at least one result
<% end %>
like image 123
Edd Morgan Avatar answered Nov 08 '22 13:11

Edd Morgan


How about

<% unless @states.empty? %>
like image 40
Andrew Haines Avatar answered Nov 08 '22 14:11

Andrew Haines


http://apidock.com/rails/ActiveRecord/Base/exists%3F/class

if @states.exists?
like image 3
rewritten Avatar answered Nov 08 '22 13:11

rewritten