【问题标题】:How to trigger conditional based on object presence on object's attribute route?如何根据对象属性路由上的对象存在触发条件?
【发布时间】:2017-01-15 23:57:34
【问题描述】:

挑战属于 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 那么我如何使用条件来触发页面上的文本,“你对这个类别没有挑战”?

我试过了……

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

但我收到错误 undefined method .categorization' for #&lt;Array:0x007fe6bfdeaed8&gt;

【问题讨论】:

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


    【解决方案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)
    

    【讨论】:

      【解决方案2】:

      检查一下:

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

      旁注:

      您可以缩短您的 scopes 定义:

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

      【讨论】:

      • 谢谢!我收到错误 undefined method 'where' for #&lt;Array:0x007fe6c3073878&gt;
      • @AnthonyGalli.com 我已经更新了答案,所以现在应该没问题了
      • 感谢旁注。我会实现的 :) Tan 的回答对我来说是一个更大的问题
      猜你喜欢
      • 2019-03-09
      • 1970-01-01
      • 1970-01-01
      • 2013-06-02
      • 1970-01-01
      • 2019-07-02
      • 1970-01-01
      • 2018-04-07
      • 1970-01-01
      相关资源
      最近更新 更多