2013-05-26 69 views
0

因爲我比Rails更新一些,所以我使用了一個快捷方式來構建一個相當複雜的(對我來說)的查詢。原始SQL到Rails ActiveRecord

好消息:我查詢工作

壞消息:我堅持用hackish的代碼和無法弄清楚如何刪除動態變量進去(這應該很容易,如果它在Rails-友好的格式)。

這裏是我的查詢(打散爲了便於閱讀):

ActiveRecord::Base.connection.select_all("SELECT DISTINCT ps.* FROM merchants merch, product_sales ps, users u, user_merchant_relations umr, memberships m

INNER JOIN marketing_efforts me ON me.id = ps.marketing_effort_id

LEFT OUTER JOIN member_sales ms ON me.id = ms.marketing_effort_id

LEFT OUTER JOIN crm_sales cs ON me.id = cs.marketing_effort_id

WHERE ((me.start < '2013-05-26' AND me.end > '2013-05-26') OR (me.start < '2013-05-26' AND me.end IS NULL)) AND (me.num_avail IS NULL OR me.num_avail > 0) AND (me.gender IS NULL OR me.gender = u.gender OR u.gender IS NULL) AND ((u.birthdate > me.birthdate_start AND u.birthdate < me.birthdate_end) OR (u.birthdate > me.birthdate_start AND me.birthdate_end IS NULL) OR (me.birthdate_start IS NULL AND me.birthdate_end IS NULL) OR u.birthdate IS NULL) AND ((ms.member_id = m.member_id AND m.user_id = u.id) OR ms.member_id IS NULL) AND (cs.crm_tier_id = umr.crm_tier_id OR cs.crm_tier_id IS NULL) AND u.id = 3 AND merch.id = 1")

任何地方'2013-05-26'出現我需要在Time.now下降。最後的u.id和merch.id也需要接受變量。

我想我可以簡單地做:???.S = ... Q = .... L = ...「,價值,價值,價值),但不工作

更新

我在這裏:

ProductSale.joins('INNER JOIN marketing_efforts ON marketing_efforts.id = product_sales.marketing_effort_id').joins('LEFT OUTER JOIN member_sales ON marketing_efforts.id = member_sales.marketing_effort_id').joins('LEFT OUTER JOIN crm_sales ON marketing_efforts.id = crm_sales.marketing_effort_id')

所以我照顧的所有連接,但我跑入的問題是,與原始的SQL,我可以很容易地定義所有我需要訪問的表格...例如:

FROM merchants merch, product_sales ps, users u, user_merchant_relations umr, memberships m

雖然我不知道如何用Rails做到這一點。其結果是,我只是得到FROM product_sales

ProductSale Load (0.3ms) SELECT "product_sales".* FROM "product_sales" INNER JOIN ....

所以,當我嘗試說,例如,users.id = 1我得到:

ActiveRecord::StatementInvalid: SQLite3::SQLException: no such column: users.id:

有什麼想法?謝謝。

+0

woaw,我覺得你老兄:(運氣好可能要使用'.include()' – Ven

回答

0

也許沒有這樣做的最好的方式,但它的工作原理和解決的主要問題(無法通過動態變量):

ProductSale.find_by_sql [ " QUE=?...R=?..Y=? ", value, value, value]