我有两个模型,用户和组。我还有一个加入表 groups_users。我在组模型中有一个关联:
has_many :groups_users
has_many :users, :through=> :groups_users
我想添加与用户关联相同但包含一些条件的pending_users。我希望将其设置为关联,以便在 sql 调用中处理所有条件。我知道有一种方法可以为同一模型设置多个访问器,即使名称与表名的实际含义无关。是类名吗?
任何帮助将不胜感激,谢谢
我有两个模型,用户和组。我还有一个加入表 groups_users。我在组模型中有一个关联:
has_many :groups_users
has_many :users, :through=> :groups_users
我想添加与用户关联相同但包含一些条件的pending_users。我希望将其设置为关联,以便在 sql 调用中处理所有条件。我知道有一种方法可以为同一模型设置多个访问器,即使名称与表名的实际含义无关。是类名吗?
任何帮助将不胜感激,谢谢
named_scope
s,他们是你的朋友你试过named_scope
在Group
模型上使用 a 吗?
因为在您真正需要数据之前,一切实际上都是一个代理,所以如果您这样做,您最终会得到一个查询:
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' }
这应该非常接近 - 更多关于has_many。
has_many :pending_users,
:through => :groups_users,
:source => :users,
:conditions => {:pending => true}
:pending 可能被称为其他东西 - 但是您确定您的待处理用户。作为旁注 - 通常当您看到用户/组模型时,该关联称为成员资格。
在用户模型中:
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])