Ruby on rails 日期比较>;=但不包括自己

Ruby on rails 日期比较>;=但不包括自己,ruby-on-rails,ruby,date,model-view-controller,methods,Ruby On Rails,Ruby,Date,Model View Controller,Methods,型号 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 有些挑战将具有相同的开始日期,这就是为什么我想要=,但现在它会在单击指向的链接时一次又一次地重新加载当前的@challenge 我怎样才能

型号

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
有些挑战将具有相同的
开始日期
,这就是为什么我想要
=
,但现在它会在单击指向
链接时一次又一次地重新加载当前的
@challenge

我怎样才能使用
=
,但是除了
@挑战
之外,所以可能在模型方法中以某种方式使用
而不是self

查看

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

为什么不比较一下被点击的挑战的id呢

添加另一个id不等于的where条件


因此,添加。其中('id!=?',单击\u id)

范围对于这类事情非常方便:

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
类挑战(日期){where(arel_表[:date_开始].gteq(日期))}
#除了这些挑战之外,所有的挑战都回来了
作用域:排除,->(id){where.not(id:id)}
def上一次用户挑战开始日期
user.challenges#获取用户挑战
.不包括(自己)#但不包括这个
.on_或_之后(开始日期)#即开始日期当天或之后
.order('U开始ASC'的日期)
.最后
结束
结束

这里还有一个链接,指向一篇关于使用作用域的精彩文章:

作用域真的很棒,特别是当你用容易链接的方式描述它们时。非常好。非常感谢。如果你愿意放纵的话,我遇到了一个超出问题范围的相关问题-现在让我们假设在相同的
开始日期有3个挑战。如果用户单击“下一步”
,它只会在质询a和质询B之间来回迭代,而不是质询C。有没有办法解决这个问题?如果您愿意,我将创建一个新问题。我将更像是在
user.challenges
上分页来解决这个问题。但是,每页仅显示1项。您可以使用
offset
limit
来执行此操作。或者,您可以在
user.challenges.load
中计算
self
的索引。前一个是
用户。挑战[index-1]
下一个世界是+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