【问题标题】:comparison of date >= but not including self比较日期 >= 但不包括自我
【发布时间】:2016-11-03 05:23:37
【问题描述】:

型号

def previous_user_challenge_date_started
  user.challenges.where('date_started >= ?', date_started).order('date_started ASC').first #date_started is a date, not datetime
end

有些挑战会有相同的date_started,这就是我想要>=的原因,但现在它会在点击link_to时一遍又一遍地重新加载当前的@challenge

我怎样才能使用>=,但除了@challenge 是个例外,所以也许可以在模型方法中以某种方式使用not self

查看

<%= link_to '← Previous', challenge_path(@challenge.previous_user_challenge_date_started), class: "prev" %>

控制器

@challenge = Challenge.find(params[:id])

【问题讨论】:

    标签: ruby-on-rails ruby date model-view-controller methods


    【解决方案1】:

    作用域对于这类事情真的很方便:

    class Challenge < ActiveRecord::Base
    
      belongs_to :user
    
      # return challenges after a particular date
      scope :on_or_after, ->(date) { where(arel_table[:date_started].gteq(date)) }
    
      # return all but these challenges
      scope :excluding, ->(id) { where.not(id: id) }
    
      def previous_user_challenge_date_started
        user.challenges             # get the users challenges
         .excluding(self)           # but not this one
         .on_or_after(date_started) # that are on or after the start date
         .order('date_started ASC')
         .last
      end
    
    end
    

    还有一篇关于使用范围的精彩文章的必填链接:Mastering ActiveRecord and AREL

    【讨论】:

    • 作用域真的很棒,尤其是当你以容易链接的方式描述它们时。
    • 非常好。谢谢!如果您愿意放纵,我遇到了超出问题范围的相关问题 - 所以现在假设有 3 个挑战相同的date_started。如果用户点击next,它只会在挑战 A 和挑战 B 之间来回迭代,而不是挑战 C。任何想法如何解决这个问题?如果您愿意,我会创建新问题。
    • 我会更多地解决这个问题,就像在user.challenges 上进行分页一样。但是,您每页仅显示 1 个项目。您可以使用offsetlimit 来执行此操作。或者,您可以在user.challenges.load 中计算出self 的索引。上一个是user.challenges[index - 1],下一个是+1。希望能给你唱歌的机会
    【解决方案2】:

    你为什么不比较点击挑战的 id。

    为 id 不等于 clicked challenge 添加另一个 where 条件。

    所以,添加 .where('id != ?', clicked_id)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-07
      • 2018-08-25
      • 2012-12-29
      相关资源
      最近更新 更多