AnthonyGalli.com AnthonyGalli.com - 2 months ago 8
Ruby Question

How to trigger conditional based on object presence on object's attribute route?

Challenges fall within one of 5 categorizations:

CATEGORIZATION = ['adventure', 'health', 'work', 'gift', 'wacky']
scope :adventure, -> { where(categorization: 'adventure') }
scope :health, -> { where(categorization: 'health') }
scope :work, -> { where(categorization: 'work') }
scope :gift, -> { where(categorization: 'gift') }
scope :wacky, -> { where(categorization: 'wacky') }


If a user clicks, for example...

<% if challenge.categorization == "work" %>
<%= link_to categorization_path(categorization: :work) do %>
<span class="glyphicon glyphicon-briefcase"></span>
<% end %>
<% elsif challenge.categorization == "gift" %> etc...


He is taken to...

Route:
http://www.livetochallenge.com/categorization?categorization=work


This page will list all his challenges that have the categorization:
work
.

@challenges = current_user.challenges.send(params[:categorization]).order("deadline ASC").select{ |challenge| challenge }
@challenges_by_date = (@challenges).group_by { |t| [t.deadline.year, t.deadline.month] }


But if the user doesn't have any challenges with the categorization:
work
then how can I use a conditional to trigger the text on the page, "You have no challenges for this category"?

I tried this...

<% if @challenges.categorization.nil? %>
You have no challenges for this category.
<% end %>


But I get the error
undefined method .categorization' for #<Array:0x007fe6bfdeaed8>

Answer

Did you try:

<% if @challenges.none?{ |challenge| challenge.categorization } %>
  You have no challenges for this category.
<% end %>

Better solution:

# assuming that the foreign key is categorization_id
@challenges.any?(&:categorization_id)
Comments