Because I'm newer to Rails than I am SQL, I took a shortcut in order to build a fairly complicated (to me, anyways) query.
Good news: I have the query working
Bad news: I'm stuck with hackish code AND can't figure out how to drop dynamic variables into it (which should be easy if it as in Rails-friendly format).
Here's my query (broken up for ease of reading):
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")
Anywhere '2013-05-26' appears I need to drop in Time.now. The u.id and merch.id at the very end also need to accept variables.
I thought I could simply do: .S=?...Q=?....L=?...", value, value, value) but that's not working.
Update
I'm here:
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')
So I'm taking care of all the joins, but the problem I'm running into is that, with the raw SQL, I could easily define all the tables I need to access ... eg:
FROM merchants merch, product_sales ps, users u, user_merchant_relations umr, memberships m
Whereas I'm not sure how to do this with Rails. As a result, I just get FROM product_sales
:
ProductSale Load (0.3ms) SELECT "product_sales".* FROM "product_sales" INNER JOIN ....
So when I try to say, for example, users.id = 1
I get:
ActiveRecord::StatementInvalid: SQLite3::SQLException: no such column: users.id:
Any thoughts? Thank you.
也许这不是最好的方法,但是它可以解决主要问题(无法传递动态变量):
ProductSale.find_by_sql [ " QUE=?...R=?..Y=? ", value, value, value]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.