【问题标题】:Scope that cooperates with a has many relationship与a合作的范围有很多关系
【发布时间】:2016-03-08 04:51:06
【问题描述】:

我有一个包含多个文档的用户模型和一个属于用户的文档模型,如下所示:

class User < ActiveRecord::Base
    has_many :documents, dependent: :destroy
end

class Document < ActiveRecord::Base
    belongs_to :user
end

我在名为archived 的文档上有一个boolean 字段。我可以通过以下方式访问属于用户的所有文档: @user = User.first @user.documents。 但我想做的是在 User 模型上创建一个范围,以显示属于该用户的所有文档,并且归档值为 true。我可以只使用模型方法,但我想弄清楚如何确定它的范围。类似于scope, -&gt; {documents.where(archived: true)} 的东西。对于 has_many 关系,我该如何做这样的事情。

【问题讨论】:

    标签: ruby-on-rails ruby model-view-controller activerecord


    【解决方案1】:

    ActiveRecord 范围的最佳品质之一是它们可以相互组合,并且具有关系。像这样在 Document 中添加这个范围:

    class Document
      scope :archived { where(archived: true) }
    end
    

    那么这段代码就会如你所愿:

    @user = User.first
    @user.documents.archived
    

    另一个需要注意的技巧是,随着作用域变得越来越复杂,您可以在经常访问的地方为它们创建简写。

    class User
      def archived_documents
        documents.archived
      end
    end
    

    【讨论】:

      【解决方案2】:

      为了回答我自己的问题,您还可以使用带有 where 子句的 has_many 关系。这是在用户模型中:

      has_many archived_documents, -> { where(archived: true) }, class_name: 'Document'
      

      【讨论】:

      • 你也可以在声明的中间定义关联的方法: has_many :documents { def complex_scope;归档的.some_other_scope;结束 } 看看吧!
      猜你喜欢
      • 2013-10-28
      • 2015-01-31
      • 2018-04-24
      • 1970-01-01
      • 2021-04-08
      • 1970-01-01
      • 2020-10-24
      • 2018-08-20
      • 1970-01-01
      相关资源
      最近更新 更多