【问题标题】:Rails, ActiveRecord: how do I get the results of an association plus some condition?Rails,ActiveRecord:我如何获得关联的结果加上一些条件?
【发布时间】:2009-08-20 19:47:46
【问题描述】:

我有两个模型,用户和组。我还有一个加入表 groups_users。 我在组模型中有一个关联:

has_many :groups_users
has_many :users, :through=> :groups_users

我想添加与用户关联相同但包含一些条件的pending_users。我希望将其设置为关联,以便在 sql 调用中处理所有条件。我知道有一种方法可以为同一模型设置多个访问器,即使名称与表名的实际含义无关。是class_name吗?

任何帮助将不胜感激,谢谢

【问题讨论】:

    标签: ruby-on-rails activerecord associations


    【解决方案1】:

    使用named_scopes,他们是你的朋友

    您是否尝试过在Group 模型上使用named_scope

    因为在您真正需要数据之前,一切实际上都是代理, 如果你这样做,你最终会得到一个查询:

    class User < ActiveRecord::Base
      named_scope :pending, :conditions => { :status => 'pending' }
    

    然后:

    a_group.users.pending
    

    确认

    我用我现有的应用程序运行了以下代码:

    Feature.find(6).comments.published
    

    它会导致这个查询(忽略第一个查询以获取特征 6):

    SELECT    * 
    FROM      `comments` 
    WHERE     (`comments`.feature_id = 6) 
      AND     ((`comments`.`status` = 'published') AND (`comments`.feature_id = 6))
    ORDER BY  created_at
    

    以下是相关型号代码:

    class Feature < ActiveRecord::Base
      has_many    :comments
    
    class Comment < ActiveRecord::Base
      belongs_to  :feature
      named_scope :published, :conditions => { :status => 'published' }
    

    【讨论】:

    • 在User模型中声明pending,而不是Group类User
    【解决方案2】:

    这应该非常接近 - 更多关于 has_many

    has_many :pending_users, 
             :through => :groups_users, 
             :source => :users, 
             :conditions => {:pending => true} 
    

    :pending 可能被称为其他名称 - 但是您确定您的待处理用户。附带说明 - 通常当您看到用户/组模型时,该关联称为成员资格。

    【讨论】:

      【解决方案3】:

      在用户模型中:

      named_scope :pending, :include => :groups_users, :conditions => ["group_users.pending = ?", true]
      

      如果您在连接表 group_users 中有一个名为“pending”的 bool 列。

      编辑: 顺便说一句,你可以这样做:

      Group.find(id).users.pending(:conditions => ["insert_sql_where_clause", arguments])
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-01-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多