2011-10-03 3 views
0

안녕하세요 수집 모델로 함께 합쳐진 게시물 모델과 컬렉션 모델이 있습니다. 사용자가 소식을 올리면 소식을 '음악'과 같은 소식 모음에 추가합니다. 그러나 모든 사용자의 컬렉션을 나열 할 때 각 게시물마다 여러 개의 '음악'항목이 있습니다. @collections = @ user.posts.map (& : 모음) .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 
,617,

후 모델 당신은 그것을 일으키는 라인을 가지고

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

답변

1

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

사용자 mdoel.

@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 차원 배열을 반환하는 것이 중요합니다. 따라서 최종 제품에서 uniq으로 전화하지 않는 한 해당 복제본은 전체 작업에서 생존합니다.

ActiveRecord 방식으로이를 피할 수 있습니다. 사용자 has_many :collections 인 경우 @user.collections에 중복이 없어야합니다. 하지만 많은 수준의 상속이있는 추한 AR 매크로 일 수 있습니다.

어쨌든 도움이 되길 바랍니다.

관련 문제