Limit columns represented in ActiveRecord

How to change ActiveRecord so that it always has a limited set of columns. I do not want all columns in a supported table to be displayed in the model. This unnecessarily inflates the ActiveRecord memory area, as well as the time taken to write a request.

There are attributes such as select ( ar.rubyonrails.org/classes/ActiveRecord/Base ) that can be used to select only a few columns. But is there a way to force ActiveRecord to never query for these columns, even though the user simply searches without specifying :select all the time.

+6
source share
2 answers

use default_scope

eg.

 class MyModel < ActiveRecord::Base default_scope select("column1, column2, column3") ... end 
+9
source

You cannot do this using scope:

 IGNORED = %w( id created_at updated_at ) scope :filtered, lambda { select( cols ) } def self.cols attribute_names = [] attributes = self.columns.reject { |c| IGNORED.include?( c.name ) } attributes.each { |attr| attribute_names << attr.name } attribute_names end Model.filtered [#<Model name: "Test 2", reg_num: "KA 02", description: "aldsfjadflkj">] 
+2
source

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


All Articles