Search code examples
ruby-on-railsruby-on-rails-4activerecord

find_by inside a scope is firing 2 queries


I am using Rails 4.2.3 and ruby 2.2.1

I have written a scope in roles model as follows:

app/models/role.rb

scope :default, -> { find_by(default: true) }

Now when I run

> Role.default

#this is the output I got.

Role Load (0.1ms)  SELECT  `roles`.* FROM `roles` WHERE `roles`.`default` = 1 LIMIT 1 
Role Load (0.1ms)  SELECT `roles`.* FROM `roles`
=> []

As you can see this fires 2 queries and returns wrong result.

I tried with class method instead of scope

def self.default
  self.find_by(default: true)
end

Now when I run

Role.default

#this is the output I got

Role Load (0.2ms)  SELECT  `roles`.* FROM `roles` WHERE `roles`.`default` = 1 LIMIT 1
=> nil

With class method find_by is working properly.

I am not able to understand what am I doing wrong here. Any help would be appreciated. Thanks in advance.


Solution

  • You shouldn't be using find_by inside a scope - find_by actually executes a database query.

    You should only be using methods that return further scopes, for example where, limit, order and so on.