2010-07-12 4 views
0

AR 쿼리에 대한 약간의 도움이 필요합니다. 이것은 내 모델처럼 보이게하는 방법입니다의 내가 모든 을 통해 기존의 범주를 반복하고 중 사용자의 출판물을 표시하거나 # {current_user.name} '같은 것을 표시하고 싶은 말은하자 이제ActiveRecord 쿼리 지원

class User < AR:B 
    has_many :publications 
end 

class Publication < AR:B 
    belongs_to :user 
    belongs_to :category 
end 

class Category < AR:B 
    has_many :publications 
end 

에 어떤 출판물이 없습니다 이 카테고리 ".

class PublicationsController < AC:B 

    def index 
    @categories = Category.find(:all, :include => :publications, :conditions => { 'publications.user_id' => current_user }) 
    end 

end 

사용자가 실제로 모든 발행물을 제공하지만 "비어있는"범주는 없습니다.

제안 사항? 당신이 has_many를 선언하는 경우, 그 다음

@categories = Category.all 

: 협회를 통해 다음과 같은 작업을 수행 할 수 있습니다 :-)

답변

0

이렇게하면 모든 종류의 객체를 제공

@categories.each do |category| 
    if category.users.include?(current_user) 
    # User has publications 
    publications = category.publications.select { |pub| pub.user == current_user } 
    else 
    # User has no publications 
    end 
end 

(이 일대 나옴 선언 :

class User < AR:B 
    has_many :publications 
    has_many :categories, :through => :publication 
end 

class Publication < AR:B 
    belongs_to :user 
    belongs_to :category 
end 

class Category < AR:B 
    has_many :publications 
    has_many :users, :through => :publication 
end 

... 경고 : drycode)

명명 된 범위를 사용하여이 작업을 수행하는 더 좋은 방법이있을 것입니다.

+0

답변을 주셔서 감사합니다.하지만 발행물에 어떻게 액세스합니까? @ category.publications는 여전히 나에게 카테고리의 모든 출판물을 줄 것입니다 ... – malloy

+0

if 문 안의 내용은 사용자가 범주에 속한 발행물을 제공해야합니다. = –

+0

Err .... think this ' 컨트롤러 코드 :/해결 된 문제, 감사합니다! – malloy

0

당신은 찾기 전화를 수정할 수 있습니다 우리는 문서의 예를하기 때문에, 해시 변형보다는 여기에 배열의 변형을 사용

@categories = Category.find(:all, :include => :publications, :conditions => [ 'publications.user_id=? OR publications.user_id IS NULL', current_user ]) 

공지 사항이 올바른 사용법이다 의미한다.

+0

이것은 출판물이있는 모든 카테고리를 제공하지만 모든 카테고리는 제공하지 않습니다. 일치하는 레코드가 없거나 뭔가 빠졌기 때문에 publications.user_id IS NULL 조건은 기본적으로 false입니다. – malloy

+0

다음과 같이 작동 할 수있는 시간에 SQL을 이해하려면 코드를 읽거나 코드를 읽어야합니다. @categories = Category.find (: all, : joins => "LEFT JOIN 발행물 ON publications.user_id = # {current_user.id} ") –

관련 문제