2013-06-26 6 views
5

을 감안할 때 2 개 액티브 관계에있는 다른 테이블에이 개 관계 :병합하는 방법 (링크) SQL 다음 생성 레일 4 개

  • 관계 a = SELECT comments.* FROM comments INNER JOIN attachments ON attachments.comment_id = comments.id WHERE attachment.name ILIKE '%foo%
  • 관계 b = SELECT attachments.* FROM attachments INNER JOIN users ON attachments.user_id = users.id WHERE users.other_conditions

이 레일에서 근무/액티브 레코드 :

puts a.merge(b).to_sql # Rails 3 
> "SELECT comments.* FROM comments INNER JOIN attachments ON attachments.comment_id = comments.id INNER JOIN users ON attachments.user_id = users.id WHERE attachment.name ILIKE '%foo% AND users.other_conditions" 

merge이 쿼리의 존재하지 않는 연결을 무시했기 때문에 효과가 있다고 생각합니다.

그러나이 4 훨씬 더 현학적 인 레일과 실패 :

puts a.merge(b).to_sql # Rails 4 
> ActiveRecord::ConfigurationError: Association named 'user' was not found on Comment; perhaps you misspelled it? 

그래서 질문은 말 그대로 레일이 정확성에 대해 걱정하지 않고 둘의 관계를 병합 할 수있는 방법이다가 (내 사양이 그 책임을)?

+0

레일스에서 ​​내부적으로 사용되는 Arel 보석을 확인하십시오. https://github.com/rails/arel 및 일부 예제/스펙은 https://github.com/rails/arel/tree/master/test에서 얻을 수 있습니다. 더 많은 통찰력. –

+0

@OtoBrglez는 거기에서 포인터를 찾을 수 없습니다. 있니? –

답변

0

모델과 모델의 관계를 좀 더 자세히 설명해 주실 수 있습니까? users을 선택

class User 
    has_many :facebook_friends 
end 

class FacebookFriend 
    belongs_to :user 
end 

a = User.where("users.first_name LIKE '%Sandy%'") 
b = FacebookFriend.where("facebook_friends.last_name LIKE '%John%'") 
a.merge(b) 

=> 사용자로드 (를 0.5ms) * users FROM WHERE (users.first_name LIKE '% 샌디 %') AND (facebook_friends.last_name LIKE : 나를 위해

는이 같은했다. '% 존 %')

=> Mysql2 :: 오류 :. 'where 절'알 수없는 열 'facebook_friends.last_name을'users를 SELECT * FROM users (users.first_name LIKE '% 샌디 %') AND (facebook_friends.last_name LIKE '% John %')

a.joins(:facebook_friends).merge(b) 

=> 사용자로드 (0.6ms)이 users를 선택한다. * users로부터 ON INNER은 facebook_friendsfacebook_friends 가입. user_uid = users. uid WHERE (users.first_name LIKE '% 샌디 %') AND (facebook_friends.last_name LIKE '% 존 %')

=> []

0

다음 놀라운 scuttle.io가 SQL 변환 :

Comment.select(Comment.arel_table[Arel.star]).where(
    Attachment.arel_table[:name].and(User.arel_table[:other_conditions]) 
).joins(
    Comment.arel_table.join(Attachment.arel_table).on(
    Attachment.arel_table[:comment_id].eq(Comment.arel_table[:id]) 
).join_sources 
).joins(
    Comment.arel_table.join(User.arel_table).on(
    Attachment.arel_table[:user_id].eq(User.arel_table[:id]) 
).join_sources 
)