Rails - Building a Query - Named Scope or?
I have the following models: Users, Groups, Conversations, ConversationParticipants( has a read boolean)
What开发者_StackOverflow中文版 I want to do is get an unread Count for a particular user in a particular group.
Should I be using a named_scope for this? If so, which model would this belong in (not sure)...
Also, I can do: @user.conversation_participations which then has the read field, problem is it does not have the group field as conversation_participations links to conversations (which has the group_id) via a conversation_id key.
Thoughts?
Thanks
You didn't show the code for the models, so I made some assumptions. Here's one way:
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
You're asking for "unread conversations belonging to a specific user and group". Since the thing being asked for is a set of Conversations, that's a natural place to put the scope.
EDIT
I see you wanted the count, not the result set. Just add .count
to the scope:
Conversation.unread(user,group).count
EDIT 2
is it possible to do something like this instead to get the #, current_user.unread(group).count ..?
Add an instance method on User:
def unread(group)
Conversation.unread(self,group)
end
Now you can call current_user.unread(group).count
If I understand the question correctly. I would use a named_scope in the ConversationParticipants called something like in_group
:
scope :in_group, lambda do
|group| joins(:conversation).where('conversation.group_id = ?', group.id)
end
I'm assuming the ConversationParticipants has belongs_to :conversation
.
Now you can do:
@user.conversation_participations.in_group( some_group )
精彩评论