Forked from ndbroadbent/arel mapped template ids.rb
Created
December 21, 2013 00:12
-
-
Save marianposaceanu/8063625 to your computer and use it in GitHub Desktop.
Using Arel instead of ActiveRecord
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module Sq | |
class Template < Sequel::Model | |
one_to_many :fields | |
def mapped_template_ids | |
FieldMapping.as(:m). | |
join(Field.named(:f), id: :field_id, template_id: id). | |
join(Field.named(:mf), id: :m__mapped_field_id). | |
distinct.select_map(:mf__template_id) | |
end | |
end | |
end | |
# Generates SQL: | |
#SELECT DISTINCT "mf"."template_id" | |
# FROM "field_mappings" AS "m" | |
# INNER JOIN "fields" AS "f" | |
# ON ( | |
# ("f"."id" = "m"."field_id") AND ("f"."template_id" = {{id}})) | |
# INNER JOIN "fields" AS "mf" | |
# ON ( | |
# "mf"."id" = "m"."mapped_field_id") | |
module AR | |
class Field < ActiveRecord::Base | |
belongs_to :template | |
belongs_to :parent, class_name: 'Field' | |
has_many :children, class_name: 'Field', foreign_key: :parent_id | |
end | |
class FieldMapping < ActiveRecord::Base | |
end | |
class Template < ActiveRecord::Base | |
has_many :fields | |
def mapped_template_ids | |
m = FieldMapping.arel_table.alias(:m) | |
f = Field.arel_table.alias(:f) | |
mf = Field.arel_table.alias(:mf) | |
query = FieldMapping.arel_table. | |
join(f).on( | |
f[:id].eq(m[:field_id]).and(f[:template_id].eq(id))). | |
join(mf).on( | |
mf[:id].eq(m[:mapped_field_id])). | |
project(mf[:template_id]). | |
from(m). | |
tap {|f| f.distinct }. | |
to_sql | |
# Generates SQL: | |
# | |
# SELECT DISTINCT "mf"."template_id" | |
# FROM "field_mappings" "m" | |
# INNER JOIN "fields" "f" | |
# ON "f"."id" = "m"."field_id" AND "f"."template_id" = {{id}} | |
# INNER JOIN "fields" "mf" | |
# ON "mf"."id" = "m"."mapped_field_id" | |
ActiveRecord::Base.connection.execute(query).to_a | |
end | |
end | |
end | |
AR::Template.last.mapped_template_ids | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment