2011-01-28 133 views
1

我有以下模型:用户,组,对话,对话参与者(有一个读取布尔值)Rails - 构建查询 - 命名范围或?

我想要做的是获得一个特定用户在一个特定的组的未读数。

我应该为此使用named_scope吗?如果是这样,这属于哪个模型(不知道)...

另外,我可以这样做:@ user.conversation_participations然后有读字段,问题是它没有组字段作为conversation_participations链接到会话(具有group_id)通过conversation_id键。

想法?

谢谢

+0

任何一个?这个问题是否令人困惑? – AnApprentice 2011-01-28 21:24:23

回答

0

如果我理解正确的问题。我会用在所谓的像in_group的ConversationParticipants一个named_scope:

scope :in_group, lambda do 
    |group| joins(:conversation).where('conversation.group_id = ?', group.id) 
end 

我假设ConversationParticipants已belongs_to :conversation

现在你可以这样做:

@user.conversation_participations.in_group(some_group) 
1

你没有显示该模型的代码,所以我做了一些假设。这里有一种方法:

class Conversation < ActiveRecord::Base 
    belongs_to :group 
    has_many :conversation_participants 
    has_many :participants, :through => :conversation_participants,\ 
    :source => :user 

    scope :unread, lambda { |user,group| includes(:group,:conversation_participants).\ 
    where(:group_id => group.id,\ 
      :conversation_participants => {:read => false,:user_id => user.id}) 
    } 
end 

您要求“未读对话属于特定用户和组”。由于被要求的东西是一组对话,所以这是放置范围的自然地方。

编辑

我看到你想要的数量,而不是结果集。只需添加.count的范围:

Conversation.unread(user,group).count 

EDIT 2

是有可能做这样的事情 这反而得到#, current_user.unread(集团).Count中.. ?

上的用户添加一个实例方法:

def unread(group) 
    Conversation.unread(self,group) 
    end 

现在,您可以拨打current_user.unread(group).count

+0

非常感谢。但有可能做这样的事情,而不是获得#,current_user.unread(group).count ..?我认为这将是更清洁,这是我没有任何运气后所经历的。思考? – AnApprentice 2011-01-28 23:25:08