cancan & many_to_many associations
I'm trying to write a rule for man开发者_运维知识库y_to_many association. Because of the association table some results are duplicated.
The code in my ability is: I have many Users that have many Groups and i want to show all Post that their author belongs to a group the same as the current_user's group. can :read, Post, :user => { :group => { :id => user.groups.collect { |g| g.id } } }
I took the generated SQL from the log and ran it in MySql query builder. The duplications appear at the SQL level.
How can i get rid of the duplicated results ?!
UPDATE 1:
The generated SQL:
SELECT posts
.* FROM posts
INNER JOIN users
ON users
.id
= posts
.user_id
INNER JOIN groups_users
ON groups_users
.user_id
= users
.id
INNER JOIN groups
ON groups
.id
= groups_users
.group_id
WHERE (groups
.id
IN (1, 2)) LIMIT 30 OFFSET 0
i updated my post to include the generated SQL. the problem is that if a user belongs to 2 groups than i get duplicated results. isn't there a way to "distinct" the results ?
You could try using the uniq
Array method after you've returned the group IDs.
Instead of:
can :read, Post, :user => { :group => { :id => user.groups.collect { |g| g.id } } }
Try:
can :read, Post, :user => {:group => { :id => user.groups.map(&:id).uniq } }
I decided to use a named scope in order to get DISTINCT results for my query.
I added this to post.rb:
named_scope :unique_posts, :select => "DISTINCT 'posts'.*"
Now i get distinct results when i call @posts.unique_posts
精彩评论