Skip to content

Instantly share code, notes, and snippets.

@darkhelmet
Created April 29, 2010 21:16
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 darkhelmet/384263 to your computer and use it in GitHub Desktop.
Save darkhelmet/384263 to your computer and use it in GitHub Desktop.
Broken scope in rails 3
class Company < ActiveRecord::Base
has_many :users
end
Loading development environment (Rails 3.0.0.beta3)
ruby-1.8.7-p249 > u = User.scoped; nil
=> nil
ruby-1.8.7-p249 > u.to_sql
=> "SELECT \"users\".* FROM \"users\""
ruby-1.8.7-p249 > u = u.id_or_name(:companies, '1'); nil
=> nil
ruby-1.8.7-p249 > u.to_sql
=> "SELECT \"users\".* FROM \"users\" WHERE (\"companies\".\"id\" = 1)"
ruby-1.8.7-p249 > u = u.id_or_name(:divisions, '2'); nil
=> nil
ruby-1.8.7-p249 > u.to_sql
=> "SELECT \"users\".* FROM \"users\" WHERE (\"divisions\".\"id\" = 2)"
ruby-1.8.7-p249 > u = User.scoped; nil
=> nil
ruby-1.8.7-p249 > u = u.where(:divisions => { :id => '2' }); nil
=> nil
ruby-1.8.7-p249 > u.to_sql
=> "SELECT \"users\".* FROM \"users\" WHERE (\"divisions\".\"id\" = 2)"
ruby-1.8.7-p249 > u = u.where(:companies => { :id => '1' }); nil
=> nil
ruby-1.8.7-p249 > u.to_sql
=> "SELECT \"users\".* FROM \"users\" WHERE (\"divisions\".\"id\" = 2) AND (\"companies\".\"id\" = 1)"
ruby-1.8.7-p249 > u = User.scoped
=> []
ruby-1.8.7-p249 > u = u.id_or_name_same_model('2'); nil
=> nil
ruby-1.8.7-p249 > u.to_sql
=> "SELECT \"users\".* FROM \"users\" WHERE (\"users\".\"id\" = 2)"
ruby-1.8.7-p249 > u = u.id_or_name_same_model('bob'); nil
=> nil
ruby-1.8.7-p249 > u.to_sql
=> "SELECT \"users\".* FROM \"users\" WHERE (\"users\".\"id\" = 2) AND (\"users\".\"name\" = 'bob')"
ruby-1.8.7-p249 >
class Division < ActiveRecord::Base
has_many :users
end
rails -v # Rails 3.0.0.beta3
rails scope_bug
cd scope_bug
bundle install
rails generate model User name:string company_id:integer division_id:integer
rails generate model Company name:string
rails generate model Division name:string
# edit files as per
rake db:migrate
bust open console
class User < ActiveRecord::Base
belongs_to :company
belongs_to :division
scope(:id_or_name, lambda { |f, v|
where(f => v.match(/^\d+$/) ? { :id => v } : { :name => v })
})
scope(:id_or_name_same_model, lambda { |v|
where(v.match(/^\d+$/) ? { :id => v } : { :name => v })
})
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment