您好我有一个职位模型和集合模型,通过收集模型连接在一起。当用户发布帖子时,他会将帖子添加到集合中,例如“音乐”。但是,当我列出所有用户的集合时,每个帖子都有多个“音乐”条目,而不仅仅是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