Skip to content

Instantly share code, notes, and snippets.

@Inviz
Last active December 15, 2015 05:29
Show Gist options
  • Save Inviz/5209744 to your computer and use it in GitHub Desktop.
Save Inviz/5209744 to your computer and use it in GitHub Desktop.
class EntriesController < ApplicationController
def index
@entries = scope
end
def show
@entry = scope.first
end
def scope
associations = Entry.associations.map {|name| name.to_s}
params[:id].split('/').inject(nil) do |scope, id|
if associations.include? id
if (scope)
scope.send(id)
else
id.singularize.titleize.constantize.dataset
end
else
if scope && scope.model.name == 'Entry' && scope.opts[:where] && scope.opts[:where].op != :IN
scope = scope.entries
end
(scope || Entry).where :entries__id => id
end
end
end
end
# STI with M:M on itself through a "relations" table
class Entry < Sequel::Model
plugin :single_table_inheritance, :kind
many_to_many :entries, :class => :Entry, :join_table => :relations, :left_key => :subject_id, :right_key => :object_id
end
class Product < Entry
end
class Slideshow < Entry
end
# Join table
class Relation < Sequel::Model
many_to_one :subject, :class => :Entry
many_to_one :object, :class => :Entry
end
--
-- 200, 1 product with id 8
-- /entries/5/6/7/products/8
SELECT `entries`.*
FROM `entries`
WHERE ( ( `entries`.`kind` IN ( 'Product' ) )
AND ( `entries`.`id` IN (SELECT `relations`.`object_id`
FROM `entries`
INNER JOIN `relations`
ON ( `relations`.`subject_id` =
`entries`.`id` )
WHERE ( ( `entries`.`id` IN (SELECT
`relations`.`object_id`
FROM `entries`
INNER JOIN `relations`
ON (
`relations`.`subject_id` =
`entries`.`id` )
WHERE ( ( `entries`.`id` IN (SELECT
`relations`.`object_id`
FROM `entries`
INNER JOIN `relations`
ON (
`relations`.`subject_id` =
`entries`.`id` )
WHERE ( `entries`.`id` = '5' )) )
AND ( `entries`.`id` = '6' ) )) )
AND ( `entries`.`id` = '7' ) )) )
AND ( `entries`.`id` = '8' ) )
LIMIT 1
-- 200 /entries/5/6/7/entries/8
-- 200 /entries/5/6/7/8
-- 200 /5/6/7/8
-- 404 /entries/5/6/7/slideshows/8
-- 404 /5/6/7/7
-- all slideshows related to all products
-- /products/slideshows
SELECT `entries`.*
FROM `entries`
WHERE ( ( `entries`.`kind` IN ( 'Product' ) )
AND ( `entries`.`id` IN (SELECT `relations`.`object_id`
FROM `entries`
INNER JOIN `relations`
ON ( `relations`.`subject_id` =
`entries`.`id` )) ) )
LIMIT 1
-- all entries related to a product
-- /products/3/entries
SELECT `entries`.*
FROM `entries`
WHERE ( ( `entries`.`kind` IN ( 'Product' ) )
AND ( `entries`.`id` IN (SELECT `relations`.`object_id`
FROM `entries`
INNER JOIN `relations`
ON ( `relations`.`subject_id` =
`entries`.`id` )
WHERE ( `entries`.`id` = '3' )) ) )
LIMIT 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment