2011-10-03 66 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宏,具有如此多的繼承層次。

無論如何,希望有所幫助!

相關問題