2011-12-01 5 views
1

을 통해 항목을 관련 얻을 나는 아래에 "이 중개인"모델 설정을대로 :레일은 두 개의 서로 다른 관계

User 
    has_many :comments 
    has_many :ratings 

Comment 
    belongs_to :user 
    belongs_to :movie 

Rating 
    belongs_to :user 
    belongs_to :movie 

Movie 
    has_many :comments 
    has_many :ratings 

가장 좋은 방법은 얻을 수 뭐죠 User과 연관 (하나의 주석 모든 Movies 또는 등급)? 이 체인 방식의 있도록

나는 (즉 User.get_movies(user_id).limit(3).order(...)) User.get_movies(user_id)를 호출 되돌려 ActiveRecord::Relation 개체를 얻을 수 있도록하고 싶습니다. 이것은 정규의 오래된 배열을 반환하고, 나는 내가 필요로하는 것보다 더 많은 데이터베이스 방법을 때리고 있다고 생각한다.

def self.get_movies(user_id) 
    user = self.where(:id => user_id).includes({:comments => :movie}, {:ratings => :movie}) 
    movies = [] 
    user.comments.each do |comment| 
    movies.push(comment.movie) 
    end 
    user.ratings.each do |rating| 
    movies.push(rating.movie) 
    end 
    movies.uniq! 
end 

답변

1
def movies 
    Movie.includes(:ratings, :comments).where("`ratings`.user_id = ? OR `comments`.user_id = ?", self.id, self.id) 
end 

테스트되지 않은,하지만 난 joins 대신도 작동 includes의를 사용하여 확실 해요.

+0

흥미로운 ... 그 여분의 관계를 설정해도 조금 해킹 된 느낌이 들다. – brittohalloran

+1

나는 has_many : movies, : through => [: comments, : ratings]과 같은 것이 거의 필요하다. t 존재 – brittohalloran

+1

@ brittohalloran : 두 번째 옵션을 시도해 볼 수 있습니까? – mbillard

관련 문제