Search code examples
ruby-on-rails

Using if statement on private method inside of show or controller page


I have a submissions_controller that has two private methods below

private

def set_submission
 @submission = Submission.find(params[:id])
end

def related_submissions
 @related_submissions = Submission.where(category_id: @submission.category_id)
end

Inside of my show.html.erb file i'm using this private method of related_submissions. If there are any related submissions with the same id, i'm showing them.

I have that next if in there to not show the current submission. The other conditional inside is checking if my image parameter is there.

<div id="submissions" class="grid grid-cols-3 gap-9">
 <% @related_submissions.each do |submission| %>
  <% next if submission == @submission %>
   <div>
    <% if submission.image.attached? %>
     <%= link_to submission do %>
      <%= image_tag submission.image, alt: submission.title %>
     <% end %>
    <% end %>
    <div class="submission-info">
     <%= link_to submission.title, submission %>
     <div>
      <%= link_to submission.url, target: :_blank do %>
       <div>
        <%= render_svg "icons/arrow-link" %>
       </div>
      <% end %>
     </div>
    </div>
   </div>
 <% end %>
</div> 

This is all working fine how I want, but I want to change the logic if there are no related submissions to show.

How can I check using this private method of related_submissions to do the below?

if there are any related submissions coming through with same category id

show related submissions with same category id

else

show this text "There are no related submissions."

end


Solution

  • This modification of before action allows you to skip next in the view

    load avoids double sql request in the view

    def related_submissions
      @related_submissions = Submission.where(category_id: @submission.category_id).where.not(id: params[:id]).load
    end
    

    This is view modification

    <% if @related_submissions.any? %>
      <% @related_submissions.each do |submission| %>
        ...
      <% end %>
    <% else %>
      <p>There are no related submissions.</p>
    <% end %>