I have 4 models, Message, Group, User, Membership
class Group < ActiveRecord::Base
has_many :memberships
has_many :users, :through => :memberships
has_many :groups_messages
has_many :messages, :through => :groups_messages, :order => "created_at desc"
named_scope :with_memberships, :include => :memberships
end
class Membership < ActiveRecord::Base
belongs_to :user
belongs_to :group
end
class User < ActiveRecord::Base
has_many :memberships
has_many :groups, :through => :memberships
end
class Message < ActiveRecord::Base
has_and_belongs_to_many :recipients, :class_name => "User"
has_many :groups_messages
has_many :groups, :through => :groups_messages
def accessible
self.groups.with_memberships.map(&:user_ids).include?(User.current.id)
end
end
Message can be posted to a Group, and if current User is a member of the group, he has a right to read it.
I am trying to check whether user is a member of the group with Message.accessible, but it produces one query to much:
Group Load (0.1ms) SELECT `groups`.* FROM `groups` INNER JOIN `groups_messages` ON `groups`.id = `groups_messages`.group_id WHERE ((`groups_messages`.message_id = 381)) AND ((`groups_messages`.message_id = 381))
Membership Load (0.1ms) SELECT `memberships`.* FROM `memberships` WHERE (`memberships`.group_id = 1)
User Load (0.1ms) SELECT `users`.id FROM `users` INNER JOIN `memberships` ON `users`.id = `memberships`.user_id WHERE ((`memberships`.group_id = 1))
I don't need User Load query - user_id is contained in Membership, so last query is useless.
I tried changing accessible method to
def accessible
self.groups.with_memberships.exists?(:user_id=>User.current.id)
end
But then it tries to use user_id in Group Load query and fails of course. How can i get rid of the last query? Rails 2.3.2