ruby-on-rails - 比较日期 >= 但不包括自身

标签 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

一些挑战将具有相同的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/

相关文章:

c# - 从 Rad Month Year Picker 获取准确值

javascript - 展开和折叠元素以及从 JavaScript 中删除静态文本

ruby-on-rails - rails 设计 edit_user_password_path

ruby-on-rails - If 语句中额外的 Ruby 行会导致 Haml 出现问题吗?

ruby - ActionCable channel 的 RSpec 测试中未定义方法 `stub_connection'

ruby-on-rails - salt 如何在 Rails 的 has_secure_password 中工作

javascript - 如何使用 javascript/jquery 反转日期格式 yyyy-mm-dd?

android - 从特定日期获取日期、月份和年份

ruby-on-rails - Declarative_authorization 似乎没有加载?

ruby-on-rails - 从 webhook 请求中解析 JSON