2018-08-08-关联扩展

一般情况下,我们在model关联(比如:has_many/belongs_to)后就会获取一组关联方法,但这些方法是有限的。

rails却赋予了我们扩展的权利,看用法

基本扩展

class Author < ApplicationRecord
  has_many :books do # 直接接 块 PS:这之间没有逗号
    def find_recent
      where('created_at > ?', 3.day.ago)
    end
  end
end

a = Author.first
a.books.find_recent

模块化扩展

module BooksExtend
  def find_recent
    where('created_at > ?', 3.day.ago)
  end
end

class Author < ApplicationRecord
  has_may :books, -> {extending BooksExtend}
end

你可能感兴趣的:(2018-08-08-关联扩展)