您好我有一個職位模型和集合模型,通過收集模型連接在一起。當用戶發佈帖子時,他會將帖子添加到集合中,例如「音樂」。但是,當我列出所有用戶的集合時,每個帖子都有多個「音樂」條目,而不僅僅是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