0

In my Show View I have:

  <div class="reviews" >
  <% @reviews.each do |review| %>
  <%= review_block review %>
  <% end %>
  </div>

In my Controller I have:

  def show    
  @review = Review.new
  @reviews = @user.reviews
  end

The idea is that if there are reviews that have been written, they are displayed on the page underneath the divs that currently exist- this part is working ok.

But if there are no reviews written, I just get nothing underneath the currently existing divs. How could I display some text like 'No reviews written, sorry!'

Ideally I'd like to show a partial, because I will be displaying more texts/ images.

I was working on something like this:

  <div class="reviews" >
  <% @reviews.each do |review| %>
  <%= review_block review if review>0 %>
  <%= else render :partial => 'layouts/no_reviews' %>
  <% end %>

But it's not working. Thanks for any help!

Chris

2 Answers 2

1
<div class="reviews" >
<% if @reviews && @reviews.present? %>
  <% @reviews.each do |review| %>
  <%= review_block review %>
<% end %>
<%= else render :partial => 'layouts/no_reviews' %>
<% end %>

e.g.

1.9.3-p327 :012 > if @abc
1.9.3-p327 :013?>   puts 'yes'
1.9.3-p327 :014?>   end
 => nil # We get noting
1.9.3-p327 :015 > @abc='lolololo'
 => "lolololo" 
1.9.3-p327 :016 > if @abc
1.9.3-p327 :017?>   puts 'yes'
1.9.3-p327 :018?>   end
yes # We get yes
Sign up to request clarification or add additional context in comments.

1 Comment

Wouldn't an empty array go through the if statement just like a non-empty array? You might want to use <% if @reviews && @reviews.present? %>
0

Try this,

<div class="reviews" >
  <% if @reviews.any? %>
    <% @reviews.each do |review| %>
      <%= review_block review %>
    <% end %>
  <% else %>
    <%= render :partial => 'layouts/no_reviews' %>
  <% end %>
</div>

2 Comments

Excellent! Works great. So easy when you see the code done out like that. Thanks also, Michael.
You are welcome :) Feel free to express your gratitude in the form of an up-vote (but only if you found the answer helpful).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.