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

时间:2016-09-08 06:53:11

标签: ruby-on-rails ruby routes conditional undefined

挑战属于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那么我如何使用条件来触发页面上的文字,&#34;您对此类别没有任何挑战#34;

我试过了......

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

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

2 个答案:

答案 0 :(得分:1)

把这个拿出来:

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

答案 1 :(得分:1)

你有没有尝试过:

<% 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)