Find_by inside the region launches 2 queries

I am using Rails 4.2.3 and ruby ​​2.2.1

I wrote the scope in the role model as follows:

application / 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 causes 2 queries and returns the wrong result.

I tried using a 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 

Using the class method, find_by works correctly.

I can’t understand what I am doing wrong here. Any help would be greatly appreciated. Thanks in advance.

+5
source share
2 answers

You should not use find_by inside the scope - find_by executes the database query.

You should only use methods that return additional areas, such as where , limit , order , etc.

+8
source

ActiveRecord, a relational object mapping system built into Rails, provides you with a set of methods to use in your areas to abstract database queries. These methods are listed here:

http://guides.rubyonrails.org/active_record_querying.html#retrieving-objects-from-the-database

In your case, you will want to use the where query.

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

+3
source

All Articles