型号
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
,所以这就是我想要>=
的原因,但现在它不断重新加载当前的@challenge
单击 link_to
时再次出现。
我如何使用>=
,但除了@challenge
,所以也许在模型中以某种方式使用not self
方法?
查看
<%= link_to '← Previous', challenge_path(@challenge.previous_user_challenge_date_started), class: "prev" %>
Controller
@challenge = Challenge.find(params[: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
这里还有一篇关于使用作用域的精彩文章的必要链接:Mastering ActiveRecord and AREL
关于ruby-on-rails - 比较日期 >= 但不包括自身,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40394377/