[英]SQL query to ActiveRecord Rails
I have here my SQL Query and it rans on my phpmyadmin perfectly: 我在这里有我的SQL查询,它在我的phpmyadmin上完美运行:
SELECT * FROM
(
SELECT requests.case_id AS case_id,
requests.request_duration_to AS due,
requests.request_to_id AS requests_to_id,
requests.kind AS kind
FROM requests AS requests
WHERE `requests`.`deleted_at` IS NULL
AND `requests`.`type` IN ('ConferenceHearingRequest')
AND (`requests`.`request_duration_to` BETWEEN '2015-08-09 16:00:00' AND '2015-08-10 15:59:59')
AND (requests.request_to_id = 1003 OR requests.created_by_id = 1003 OR requests.request_to_cc_ids LIKE '1003')
ORDER BY created_at DESC
) AS requests
UNION
(
SELECT records.case_id AS case_id,
records.record_duration_to AS due,
records.approve_to_id AS records_to_id,
records.type_of_request AS kind
FROM records AS records
WHERE `records`.`deleted_at` IS NULL
AND `records`.`type` IN ('ConferenceHearingRecord')
AND (`records`.`record_duration_to` BETWEEN '2015-08-09 16:00:00' AND '2015-08-10 15:59:59')
AND (records.approve_to_id = 1003 OR records.created_by_id = 1003 OR records.cc_to_ids LIKE '1003')
ORDER BY created_at DESC
)
My question is how can I make it to Rails way? 我的问题是如何使它达到Rails的方式?
你可以写
@result = ActiveRecord::Base.connection.execute("YOUR SQL QUERY WILL GO HERE")
You can fetch records in tow queries and union
in ruby. 你可以取拖查询和记录union
的红宝石。 ie. 即。
requests = Request.select('requests.case_id AS case_id,
requests.request_duration_to AS due,
requests.request_to_id AS requests_to_id,
requests.kind AS kind').where(" conditions ").order('created_at DESC')
records = Record.select(" records.case_id AS case_id,
records.record_duration_to AS due,
records.approve_to_id AS records_to_id,
records.type_of_request AS kind ").where(" conditions ").order('created_at DESC')
And then union in ruby - 然后在红宝石中结合-
results = requests | records
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.