2016-11-15 2 views
0

두 모델이 다음과 같이 서로 연관되어 있습니다.레일 5 - Activerecord 연관 검색어

class Comment < ApplicationRecord 
    belongs_to :user 
end 

class User < ActiveRecord::Base 
    has_many :comments 
end 

기록 쿼리에 따라

comments_list = Comment.where(:post_id => post_id, :is_delete => false).joins(:user).select('comments.*,users.*') 

로거

SELECT comments.*,users.* FROM `comments` INNER JOIN `users` ON `users`.`id` = `comments`.`user_id` WHERE `comments`.`post_id` = '81' AND `comments`.`is_delete` = 0. 

이 매우 ligitimate 쿼리를 생성하는 것 같다에서 다음 MySQL의 쿼리를 생성하지만, comments_list 객체는 의견 테이블에서 열을 포함한다.

감사

그것은 당신이 당신이 옆에 코멘트에 사용자 이름을 표시하려면, 수행하려는 작업에 따라 달라집니다

답변

1

는, 머트 B.의 대답은 당신이해야 할 모든 include(:user)하고 사용자로부터, 괜찮습니다 댓글 목록이이 같은 것을 할 때 함께 가져됩니다

comments_list = Comment.where(:post_id => post_id, :is_delete => false).joins(:user).select('comments.*,users.*') 
comments_list.each do |comment| 
    puts "#{comment.text} by #{comment.user.name}" 
end 

또는 어쩌면 당신은 적어도 하나의 코멘트가있는 경우에만 사용자가 원하는 경우, 당신이 할 수있는 코멘트 테이블에 user_ids에서 항상 선택 사용자 :

User.where(id: Comment.select(:user_id)) 
+0

예 @Macelo Risoli - 감사합니다. 이것은 응답을 다시 클라이언트 (브라우저), 루프를 통해 반복하여 다른 해시 건물 응답을 반환하려면 컨트롤러에서이 쿼리를 수행하는 경우이 결과를 번역 할 의미합니다. – user3775217

+0

첫 번째 답변 - 마지막 para http://stackoverflow.com/questions/19175084/activerecord-query-through-multiple-joins – user3775217