挑战属于以下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>
发布于 2016-09-08 15:00:11
你有没有尝试:
<% 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)发布于 2016-09-08 15:00:03
看看这个:
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) }
endhttps://stackoverflow.com/questions/39384362
复制相似问题