如何根据对象属性路由上的对象存在来触发条件?

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

挑战属于 5 个分类之一:

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

他被带到...

路线:http://www.livetochallenge.com/categorization?categorization=work

此页面将列出他的所有分类挑战: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] }

但是如果用户对分类没有任何挑战:work 那么我如何使用条件触发页面上的文本,"You have no challenges for this category"?

我试过了...

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

但我收到错误 undefined method .categorization' for #<Array:0x007fe6bfdeaed8>

看看这个:

if @challenges.none? { |c| c.categorization }

旁注:

您可以缩短 scope 的定义:

  CATEGORIZATION = %w(adventure health work gift wacky).freeze
  CATEGORIZATION.each do |categorization|
    scope categorization.to_sym, -> { where(categorization: categorization) }
  end

你试过了吗:

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

更好的解决方案:

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