问题
I am trying to allow my Rails App some advanced functionality in way of creating relationships. I am running MySQL as the back-end. The query below runs just fine in PHPMyAdmin, but upon attempted execution in rails, it does nothing, no errors and no database writes....
I use active record to create the relationships between Campaign and Location, and then the query below should work to build afterward in campaign_metros table:
class CampaignLocation < ActiveRecord::Base
belongs_to :campaign
belongs_to :location
after_touch :create_campaign_metro
private
def create_campaign_metro
@sql_insert="INSERT INTO `campaign_metros` (`campaign_id`,`metro_id`, `created_at`,`updated_at`)
SELECT f.`campaign_id`, f.`city_id`, NOW(), NOW()
FROM (SELECT d.`campaign_id`, d.`city_id`
FROM (SELECT c.`campaign_id`, c.`city_id`
FROM (SELECT distinct a.`campaign_id`, b.`city_id`
FROM `campaign_locations` a
INNER JOIN `locations` b
ON a.`location_id` = b.`id`) c) d
LEFT JOIN `campaign_metros` e
ON e.`campaign_id` = d.`campaign_id` and
e.`metro_id` = d.`city_id`
WHERE e.`metro_id` is null and e.`campaign_id` is null) f;"
ActiveRecord::Base.connection.execute(@sql_insert)
end
end
I know from MySQL DELETE FROM with subquery as condition, in answer number two by CodeReaper, that MySQL requires another level of aliases when dealing with subqueries, but running my query in Rails does nothing at all.
How can I get this to work?
来源:https://stackoverflow.com/questions/27626194/active-record-insert-into