Skip to content

Instantly share code, notes, and snippets.

@neerajsingh0101
Created May 12, 2010 11:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save neerajsingh0101/398486 to your computer and use it in GitHub Desktop.
Save neerajsingh0101/398486 to your computer and use it in GitHub Desktop.
# Following code has been tested with rails edge
class CreateUser < ActiveRecord::Migration
def self.up
create_table :users do |t|
t.string :name
t.string :type
end
end
def self.down
drop_table :users
end
end
class User < ActiveRecord::Base
end
class Agent < User
end
class SuperAgent < Agent
end
rails c
> Agent.find_by_name 'agent'
SELECT "users".* FROM "users" WHERE ("users"."type" = 'Agent') AND ("users"."name" = 'agent') LIMIT 1
> SuperAgent # just load this class
> Agent.find_by_name 'agent'
SELECT "users".* FROM "users" WHERE (("users"."type" = 'Agent' OR "users"."type" = 'SuperAgent')) AND ("users"."name" = 'agent') LIMIT 1
# Note that in the above case by loading SuperAgent the sql generated
# by Agent.find_by_name 'agent' has changed and now # the sql also includes SuperAgent
# However note that this behavior is not consistent if query is performed on the lowest level class.
rails c
> User.find_by_name 'agent'
SELECT "users".* FROM "users" WHERE ("users"."name" = 'agent') LIMIT 1
> Agent
> SuperAgent
> User.find_by_name 'agent'
SELECT "users".* FROM "users" WHERE ("users"."name" = 'agent') LIMIT 1
# Note that this is an issue only in development node. In production mode all the classes would be pre loaded.
@fxn
Copy link

fxn commented May 12, 2010

In the first case SuperAgent is ORed because all superagents are agents. But of course AR needs to know about that class, otherwise it just does not have the information.

In the last case, User is the root of the hierarchy, and thus all records are users and no further constraints are needed. That is why you do not see the types ORed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment