Skip to content

Instantly share code, notes, and snippets.

@olivere
Created December 6, 2010 17:17
Show Gist options
  • Save olivere/730591 to your computer and use it in GitHub Desktop.
Save olivere/730591 to your computer and use it in GitHub Desktop.
Problem with STI and scopes
# Let's start off with a company and a buyer model
class Company < ActiveRecord::Base
has_many :users
end
class Buyer < Company
# Makes sure that +user+ only gets the buyers she may see.
# If +user+ is nil we assume anonymous.
def self.for(user)
buyers = Buyer.scoped
if user
buyers = buyers.where(:id => user.company_id)
else
# Some way to make sure nothing is returned
buyers = buyers.where(:id => 0)
end
buyers
end
end
# Now with standard Rails (no meta_where):
Buyer.for(nil).to_sql
=> "SELECT `companies`.* FROM `companies` WHERE (`companies`.`type` = 'Buyer') AND (companies.id = 0)"
Buyer.for(nil).where(:id => 2).to_sql
=> "SELECT `companies`.* FROM `companies` WHERE (`companies`.`type` = 'Buyer') AND (companies.id = 0) AND (`companies`.`id` = 2)"
# Now with meta_where included in Gemfile:
Buyer.for(nil).to_sql
=> "SELECT `companies`.* FROM `companies` WHERE (`companies`.`type` = 'Buyer') AND (`companies`.`id` = 0)"
Buyer.for(nil).where(:id => 2).to_sql
=> "SELECT `companies`.* FROM `companies` WHERE (`companies`.`type` = 'Buyer') AND (`companies`.`id` = 2)"
# Still testing what exactly causes this issue is caused with STI only...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment