对于使用较新版本的 Rails 遇到此问题的任何人,has_many 的第二个参数自 Rails 4.0.2 以来一直是可选范围。来自the docs 的示例(参见范围和选项示例)包括:
has_many :comments, -> { where(author_id: 1) }
has_many :employees, -> { joins(:address) }
has_many :posts, ->(blog) { where("max_post_length > ?", blog.max_post_length) }
has_many :comments, -> { order("posted_on") }
has_many :comments, -> { includes(:author) }
has_many :people, -> { where(deleted: false).order("name") }, class_name: "Person"
has_many :tracks, -> { order("position") }, dependent: :destroy
如前所述,您也可以将块传递给has_many。 “这对于添加新的查找器、创建器和其他工厂类型的方法以用作关联的一部分很有用。” (same reference - 请参阅扩展)。
这里给出的例子是:
has_many :employees do
def find_or_create_by_name(name)
first_name, last_name = name.split(" ", 2)
find_or_create_by(first_name: first_name, last_name: last_name)
end
end
在更现代的 Rails 版本中,可以编写 OP 的示例:
class Log < ApplicationRecord
has_many :items, -> { order(some_col: :desc) }
end
请记住,这具有默认作用域的所有缺点,因此您可能更愿意将其添加为单独的方法:
class Log < ApplicationRecord
has_many :items
def reverse_chronological_items
self.items.order(date: :desc)
end
end