【问题标题】:Turn 'if' statement into a named scope将“if”语句转换为命名范围
【发布时间】:2015-02-26 11:47:18
【问题描述】:
<% @training_dates.reverse.each do |t| %>
  <% if t.candidate_limit != Subscription.group(:training_date_id).count[t.id] %>
      <%= t.name %>
  <% end %>
<% end %>

我想把这个if 语句变成一个作用域,这样我就可以做@training_dates.(scope).reverse.each

【问题讨论】:

  • 我认为您需要添加一些关于 @traqining_dates 变量、Subscription 模型的详细信息,以及为模型而不是变量添加的范围为:Subscription.training_date_count 以返回 training_date 计数
  • 为什么不使用我们帮助您在Your Previous Question 中定义的范围。这将是等价的。所以@training_dates = TrainingDate.not_full.reverse 然后@training_dates.each do |t|。当您说“不适用于新帖子”时,我不确定您对该帖子的评论意味着什么。它的工作原理是根据拨打电话的时间,很明显,如果有人在通话后注册,除了通知用户 TrainingDate 现已满员之外,您无能为力。

标签: ruby-on-rails ruby scope named-scope


【解决方案1】:

我不知道你的其他型号是什么,但training_date 型号的示例范围应该如下(rails 4):

class TrainingDate
   scope :sss, -> do
      where.not(candidate_limit: Subscription.group(:training_date_id).count(:id))
           .order(:desc)
   end
end

然后:

sss.each { |t| t.name }

对于其他rails 版本,您必须使用 gem。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-04-09
    • 1970-01-01
    • 2023-04-08
    • 2014-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多