Skip to content

Instantly share code, notes, and snippets.

@iamvery
Last active August 29, 2015 14:06
Show Gist options
  • Save iamvery/8dc3f538d3b17afffb13 to your computer and use it in GitHub Desktop.
Save iamvery/8dc3f538d3b17afffb13 to your computer and use it in GitHub Desktop.
Scopes behavior in ActiveRecord 3

Example of interesting behavior of scopes in ActiveRecord 3.

● master ~/Code/OSS/scope-v-method » bundle console
Resolving dependencies...
irb(main):001:0> require_relative 'foo'
=> true
irb(main):002:0> Foo.bar
=> []
irb(main):003:0> _.class
=> Array
irb(main):004:0> Foo.baz
=> []
irb(main):005:0> _.class
=> ActiveRecord::Relation
irb(main):006:0> Foo.create! name: 'foo'
=> #<Foo id: 1, name: "foo">
irb(main):007:0> Foo.by_name_s('foo')
=> []
irb(main):008:0> _.class
=> Array
irb(main):009:0> Foo.by_name_m('foo')
=> ["foo"]
irb(main):010:0> _.class
=> Array

Also see the same example in ActiveRecord 4

require 'active_record'
class Foo < ActiveRecord::Base
establish_connection adapter: 'sqlite3', database: ':memory:'
connection.create_table :foos do |t|
t.string :name
end
scope :bar, ->() do
[:bar]
end
scope :baz, ->(){}
scope :by_name_s, ->(name) do
scoped = where(name: name)
scoped.map(&:name)
end
def self.by_name_m(name)
scoped = where(name: name)
scoped.map(&:name)
end
end
source 'https://rubygems.org'
gem 'activerecord', '~>3.0'
gem 'sqlite3'
GEM
remote: https://rubygems.org/
specs:
activemodel (3.2.19)
activesupport (= 3.2.19)
builder (~> 3.0.0)
activerecord (3.2.19)
activemodel (= 3.2.19)
activesupport (= 3.2.19)
arel (~> 3.0.2)
tzinfo (~> 0.3.29)
activesupport (3.2.19)
i18n (~> 0.6, >= 0.6.4)
multi_json (~> 1.0)
arel (3.0.3)
builder (3.0.4)
i18n (0.6.11)
multi_json (1.10.1)
sqlite3 (1.3.9)
tzinfo (0.3.41)
PLATFORMS
ruby
DEPENDENCIES
activerecord (~> 3.0)
sqlite3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment