Skip to content

Instantly share code, notes, and snippets.

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

Example of interesting behavior of scopes in ActiveRecord 4.

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

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', '~>4.0'
gem 'sqlite3'
GEM
remote: https://rubygems.org/
specs:
activemodel (4.1.6)
activesupport (= 4.1.6)
builder (~> 3.1)
activerecord (4.1.6)
activemodel (= 4.1.6)
activesupport (= 4.1.6)
arel (~> 5.0.0)
activesupport (4.1.6)
i18n (~> 0.6, >= 0.6.9)
json (~> 1.7, >= 1.7.7)
minitest (~> 5.1)
thread_safe (~> 0.1)
tzinfo (~> 1.1)
arel (5.0.1.20140414130214)
builder (3.2.2)
i18n (0.6.11)
json (1.8.1)
minitest (5.4.1)
sqlite3 (1.3.9)
thread_safe (0.3.4)
tzinfo (1.2.2)
thread_safe (~> 0.1)
PLATFORMS
ruby
DEPENDENCIES
activerecord (~> 4.0)
sqlite3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment