【问题标题】:Order by two attributes, one of them in a child model (rails 4)按两个属性排序,其中一个在子模型中(rails 4)
【发布时间】:2014-11-11 21:19:05
【问题描述】:

我的应用有两个模型,ClassSection 和 ClassDate(这些模型中的课程是指学校的课程)。

以下是模型:

class ClassSection < ActiveRecord::Base
  default_scope { order('code ASC') }
  scope :published, -> { order('code ASC').order('id ASC').where(published: true) }

  has_many :class_dates, dependent: :destroy

  def begins
    if self.class_dates.count > 0
      self.class_dates.order('start_time ASC').first.start_time
    else
      nil
    end
  end

  def ends
    if self.class_dates.count > 0
      self.class_dates.order('start_time ASC').last.start_time
    else
      nil
    end
  end

  def date_range
    if self.begins != nil && self.ends != nil
      "#{self.begins.to_formatted_s(:class_date)} to #{self.ends.to_formatted_s(:class_date)}"
    else
      "No dates"
    end
  end
end

class ClassDate < ActiveRecord::Base
  scope :upcoming, -> { where("start_time >= ? ", Time.now.to_date).order('start_time ASC').limit(10) }
  default_scope { order('start_time ASC' ) }

  belongs_to :class_section
end

在 :published ClassSections 的范围内请注意,我首先根据类的代码(如 ENG 101)进行排序,然后按 id 进行排序。我宁愿根据它的 start_time(这是 ClassDate 的日期时间属性)对第一个 ClassDate 进行排序。如何编写按最早 start_time 排序的范围?

如需解答,请查看Sorting a hash using a method from the corresponding model

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-4 scope has-many


    【解决方案1】:

    除非确实需要,否则不要使用 default_scope。


    您必须在其属性中包含与订单的关系:

    scope :ordered, { includes(:class_dates).order('class_dates.start_time DESC, class_sections.codes ASC') }
    

    【讨论】:

    • 根据您的回答,我正在使用:scope :ordered, -> { includes(:class_dates).order('class_dates.start_time ASC, class_sections.code ASC') }像我希望的那样工作。我希望将具有相同代码的类组合在一起。我试着简单地把它翻过来:scope :ordered, -> { includes(:class_dates).order('class_sections.code ASC, class_dates.start_time ASC') } 我得到了这个错误: SQLite3::SQLException: no such column : class_dates.start_time: SELECT "class_sections".* FROM "class_sections" ORDER BY class_sections.code ASC, class_dates.start_time ASC
    猜你喜欢
    • 2012-12-25
    • 1970-01-01
    • 1970-01-01
    • 2013-08-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多