2011-03-15 41 views
1

訂購habtm設備和設備habtm命令。基於HABTM的查找無硬編碼SQL片段

我需要找到訂單,讓所有指定的設備

我做如下:

devices = Device.all :conditions => {:name => params[:devices].split(",")} 
@orders = Order.all :joins => :devices, :conditions => {:devices => devices} 

它產生下面的SQL:

SELECT "orders".*

FROM "orders"

INNER JOIN "orders_devices" ON "orders_devices".order_id = "orders".id

INNER JOIN "devices" ON "devices".id = "orders_devices".device_id

WHERE ("orders"."devices" IN (110330561,530240381)) ORDER BY date DESC)

查詢的最後一個字符串爲不正確,當然,我得到一個錯誤:

SQLite3::SQLException: no such column: orders.devices

爲什麼我得到這個結果?

我該如何解決這個問題,而不指定SQL查詢的片段,像:

:conditions => ['devices.id in (?)',[1,2]] 

回答

3

也許只是這個?

@orders = Order.all(:joins => :devices, :conditions => {"devices.id" => devices}) 
+0

它的工作原理,但它有什麼辦法可以避免「devices.id」? – AntonAL 2011-03-15 16:04:31

+0

我甚至不知道表達它的不同方式。它是可讀的,我不會認爲它是一個SQL片段(它表示「設備的ID」)。在* arel *你可以做一些像'Devices.arel_table [:id] .in(devices)''但我懷疑這是更好的。在* DataMapper *你的例子可以工作,但DM有其他問題。 – 2011-03-15 16:24:54