2011-10-03 29 views
0

您好我有一个职位模型和集合模型,通过收集模型连接在一起。当用户发布帖子时,他会将帖子添加到集合中,例如“音乐”。但是,当我列出所有用户的集合时,每个帖子都有多个“音乐”条目,而不仅仅是1. 我用@collections = @ user.posts.map(&:collections)抓取集合.flatten,如果我在最后添加.uniq没有重复(@collections = @ user.posts.map(&:collections).flatten.uniq)但是有人可以解释为什么我必须这样做吗?非常感谢。为什么我有相同的集合名称的每个职位的重复

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 

的意见/用户/ show.html.erb

<h1>Collections</h1> 

    <% @collections.each do |collection| %> 
    <%= link_to collection.name, user_collection_posts_path(@user, link_name(collection)) %><br /> 
    <% end %> 

收集模型

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模型

class Collectionship < ActiveRecord::Base 
    belongs_to :post 
    belongs_to :collection 
    has_one :user, :through => :post 
    attr_accessible :post_id, :collection_id 
end 

岗位模型

belongs_to :user 
    has_many :collectionships 
    has_many :collections, :through => :collectionships 

用户mdoel

has_many :posts, :dependent => :destroy 
has_many :collections, :through => :posts 

回答

1

你就是我的导致了它的线。下面是我采取为什么你看到你做什么(只是该行的评价每一步的扩展):

@user.posts #=> 
[ 
    <Post1: 
     id: 1492 
     collections: ['history', 'spain'] 
    >, 
    <Post2: 
     id: 1912 
     collections: ['history', 'shipwrecks'] 
    > 
] 

@user.posts.map(&:collections) #=> 
[ 
    ['history', 'spain'], 
    ['history', 'shipwrecks'] 
] 

@user.posts.map(&:collections).flatten #=> 
[ 
    'history', 
    'spain', 
    'history', 
    'shipwrecks' 
] 

所以你可以看到,每一个为每个岗位,post.collections回报所有集合该帖子是在(应该)。并且flatten方法不关心是否有重复 - 它只关心返回单个1-D数组。因此,除非您在最终产品上拨打uniq,否则这些重复部分将在整个操作过程中保留下来。

我相信有一个ActiveRecord的方式来避免这种情况:如果用户has_many :collections,那么@user.collections不应该有任何重复。虽然可能是一个丑陋的AR宏,具有如此多的继承层次。

无论如何,希望有所帮助!

相关问题