Hi I have a posts model and a collections model, joined together by a collectionship model. When a user makes a post he adds the post to a collection, such as ‘music’. However, when I list all the user’s collections there are multiple ‘music’ entries for each post made instead of just 1.
I’m grabbing the collections with @collections = @user.posts.map(&:collections).flatten, if I add a .uniq on the end get no duplicates (@collections = @user.posts.map(&:collections).flatten.uniq) But could someone explain why I’d have to do this??? Thanks a lot.
UsersController
def show
@user = User.find(params[:id]) rescue nil
@posts = @user.posts.paginate(:per_page => "10",:page => params[:page])
@title = @user.name
@collections = @user.posts.map(&:collections).flatten
end
views/users/show.html.erb
<h1>Collections</h1>
<% @collections.each do |collection| %>
<%= link_to collection.name, user_collection_posts_path(@user, link_name(collection)) %><br />
<% end %>
collection model
class Collection < ActiveRecord::Base
mount_uploader :image, CollectionUploader
attr_accessible :name, :image, :user_id
has_many :collectionships
has_many :users, :through => :posts
has_many :posts, :through => :collectionships
end
collectionship model
class Collectionship < ActiveRecord::Base
belongs_to :post
belongs_to :collection
has_one :user, :through => :post
attr_accessible :post_id, :collection_id
end
post model
belongs_to :user
has_many :collectionships
has_many :collections, :through => :collectionships
user mdoel
has_many :posts, :dependent => :destroy
has_many :collections, :through => :posts
You’ve got the line that’s causing it. Here’s my take on why you’re seeing what you do (just an expansion of each step of evaluation of that line):
So you can see that each for each post,
post.collectionsreturns all the collections that post is in (as it should). And theflattenmethod doesn’t care if there are duplicates or not – it just cares about returning a single, 1-D array. So those duplicates survive throughout the whole operation, unless you calluniqon the final product.I believe there’s an ActiveRecord way to avoid this as well: If a User
has_many :collections, then@user.collectionsshouldn’t have any duplicates. Might be an ugly AR macro, though, with so many levels of inheritance.Anyway, hope that helps!