Rails: has_many check in view

If I have...

class Bunny < ActiveRecord::Base
  has_many :carrots
end

... how can I check in the view if it @bunnyhas carrots? I want to do something like this:

<% if @bunny.carrots? %>
  <strong>Yay! Carrots!</strong>
  <% for carrot in @bunny.carrots %>
    You got a <%=h carrot.color %> carrot!<br />
  <% end %>
<% end %>

I know what @bunny.carrots?doesn't work - what would it be?

+3
source share
4 answers
<% if @bunny.carrots.any? %>
  <strong>Yay! Carrots!</strong>
  <% for carrot in @bunny.carrots %>
    You got a <%=h carrot.color %> carrot!<br />
  <% end %>
<% end %>
+8
source
unless @bunny.carrots.empty? 

will also work

+3
source

or:

  if @bunny.carrots.length>0

or

unless @bunny.carrots.nil? || @bunny.carrots.length>0

or

  if @bunny.carrots.any?

by the way, you will find more collection operations if you use irb or script / console with the requirement "irb / completion"

+1
source

@bunny.carrotsis an array, so you can consider it as such by calling the array methods on it, for example.unless @bunny.carrots.empty?

0
source

Source: https://habr.com/ru/post/1699687/


All Articles