ActiveRecord scope returns an array

I have a scope that returns Array instead of ActiveRecord Relation when it is called, but if I call methods within the scope, it returns ActiveRecord Relation .

 scope :beta_user, -> { joins(:config).where("config_type = 'Model' AND opts #>> '{beta}' = 'true'") } # Calling scope directly Model.beta_user # => [Model1, Model2, Model3] Model.beta_user.class # => Array # Calling scope definition Model.joins(:config).where("config_type = 'Model' AND opts #>> '{beta}' = 'true'") => [Model1, Model2, Model3] Model.joins(:config).where("config_type = 'Model' AND opts #>> '{beta}' = 'true'").class => Model::ActiveRecord_Relation 

So my question is what happens to inconsistent return types? After that, I cannot bind other areas (I can still bind them before that), and I cannot use other AR Relation methods such as #order and #pluck .

From what I see in the console, it looks like calling Model.beta_user.class is still executing the request, while Model.joins(:config).where("config_type = 'Model' AND opts #>> '{beta}' = 'true'") does not execute the request. I thought that the area should not be executed until it is needed to optimize the chains / queries.

+6
source share
1 answer

The object does return a relationship object, however, it will convert it when necessary, when you launch the area in the console, it will try to check it and will perform the conversion.

But try this, it should work:

 scope = Model.beta_user # pluck should work scope.pluck(:id) 

And all other methods, such as first , last , count , all , etc. must work

0
source

Source: https://habr.com/ru/post/1011567/


All Articles