2011-02-18 53 views
3

我有一個範圍:Rails的,範圍或並加入

includes(:countries).where("profiles.sector = :sector OR advices.sector = :sector", :sector => sector) 

它生成的SQL語句:

SELECT `profiles`.* FROM `profiles` INNER JOIN `advices` ON `advices`.`profile_id` = `profiles`.`id` WHERE (profiles.sector = 'Forestry_paper' OR advices.sector = 'Forestry_paper') 

(是的,我的國家,我Profile,在我Country模型)

不幸的是,OR似乎失敗:

它做沒有提供只有適當的部門,但沒有相關的建議的配置文件。思考?

回答

7

您正在進行INNER JOIN,因此它需要配置文件有相應的建議。請改爲嘗試以下操作:

Profile 
    .joins("LEFT JOIN advices ON advices.profile_id = profiles.id") 
    .where("profiles.sector = :sector OR advices.sector = :sector", :sector => sector) 

這還包括沒有建議的配置文件。

+0

謝謝:)沒有更好的Rails的辦法寫下來?而且,如何用LEFT JOIN鏈接連接? – apneadiving 2011-02-18 22:30:37

+0

沒關係,只是一個AND就完美了 – apneadiving 2011-02-18 22:35:05

+0

沒有其他Rails的方式來寫入連接。 joins方法僅適用於內部聯接(http://guides.rubyonrails.org/active_record_querying.html#joining-tables) – 2011-02-18 22:37:00

7

你可以做外連接由includes後指定用哈希where子句:

Post.includes(:comments).where(:comments=>{:user_id=>nil}) 

生產:

Post Load (0.5ms) SELECT "posts"."id" AS t0_r0, "posts"."created_at" AS t0_r1, 
    "posts"."updated_at" AS t0_r2, "comments"."id" AS t1_r0, "comments"."user_id" 
    AS t1_r1, "comments"."post_id" AS t1_r2, "comments"."content" AS t1_r3, 
    "comments"."created_at" AS t1_r4, "comments"."updated_at" AS t1_r5 
    FROM "posts" LEFT OUTER JOIN "comments" ON "comments"."post_id" = "posts"."id" 
    WHERE ("comments"."user_id" IS NULL) 

瑞恩比格寫了helpful blog post about this

編輯

要知道,這種技術是或多或少的方式軌道的副作用,構建了渴望加載協會SQL。正如接受的答案中所建議的那樣,顯式的LEFT JOIN更加健壯。