【问题标题】:How to query scoped 'previous' and 'next' records (ActiveRecord & PostGres) rails 4.2如何查询范围内的“上一个”和“下一个”记录(ActiveRecord 和 PostGres)rails 4.2
【发布时间】:2015-07-31 00:01:16
【问题描述】:

我正在实现一个带有用户模型的待办事项列表和一个带有日期属性的列表模型。 在用户展示页面上,我检索了今天的待办事项列表。

如何查询用户前一天和/或第二天的待办事项列表。

欢迎所有见解,谢谢!

class User < ActiveRecord::Base
  before_save { self.email = email.downcase }
  before_save { self.username = username.downcase }
  has_many :to_do_lists, dependent: :destroy
  has_many :tasks, dependent: :destroy
  validates_presence_of :first_name, :last_name
  VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-]+(?:\.[a-z\d\-]+)*\.[a-z]+\z/i
  VALID_USERNAME_REGEX = /\A[a-z_0-9]+\z/i
  validates :email, presence: true,
        format: { with: VALID_EMAIL_REGEX },
        uniqueness: { case_sensitive: false }
  validates :username, presence: true,
        format: { with: VALID_USERNAME_REGEX },
        uniqueness: { case_sensitive: false }
  def name
     [first_name, last_name].compact.join(' ')
  end
end

和列表模型

class ToDoList < ActiveRecord::Base
  belongs_to :user
  has_many :tasks, dependent: :destroy
  validates_presence_of :user_id
  validates :date, presence: true, 
        uniqueness: {scope: :user_id}
end

【问题讨论】:

  • 如果您展示模型可能会有所帮助。

标签: ruby-on-rails postgresql ruby-on-rails-4 activerecord dynamic-queries


【解决方案1】:

Rails 为Time 添加了许多有用的方法,使这种类型的查询非常直观。由于您确认用户每天只有一个待办事项列表:

 @next_day_list = @user.to_do_lists.find_by_date(Date.today.tomorrow)
 @prev_day_list = @user.to_do_lists.find_by_date(Date.today.yesterday)

【讨论】:

    猜你喜欢
    • 2011-07-24
    • 2012-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多