I'm trying to limit the number of albums a user can create by only showing a link to a new album if the number of albums is greater than 3. The error I am getting says 'compared with non class/module'
<% if @albums < 3 %>
<div class="all-albums" id="position-albums">
<%= link_to 'New Album', "/albums/new", :style => "text-decoration:none; color:black; font-size: 20px;" %>
<div class="plus-sign">
<%= link_to '+', "/albums/new", :style => "text-decoration:none; color:black; font-size:80px; color:#85adad;" %>
</div>
</div>
<% end %>
If @albums
is an AR collection, you can call size
, length
or count
methods to identify the number of objects within it. For instance:
<% if @albums.size <= 3 %>
Also, you should use <=
instead of <
, according to your post.
All of these 3 methods differ from each other and you should pick the one you need depending on your situation:
calling count
(without the block) is going to execute a SELECT COUNT(*)
query. You should use this method in case it's crucial for you to get the latest calculation result from db instead of using a cached version based on the loaded results or in case you don't actually need the records themselves, just the count calculations.
calling length
is going to execute a SELECT *
query and call size
method on the resulting collection (without producing any further queries to db). It's preferable in case you are going to use the underlying records anyway.
calling size
on the collection that is not loaded yet is going to execute a SELECT COUNT(*)
. Otherwise size
method is going to be called on the loaded collection (without producing any further queries to db).