How to change ActiveRecord so that it always has a restricted set of columns. I dont want all the columns in the backened table to present in the Model. This unnecessarily bloats the ActiveRecord's memory footprint as well as the time taken to query the record.
There are attributes like select (ar.rubyonrails.org/classes/ActiveRecord/Base) which can be used to SELECT only few columns. But is there any way we can force ActiveRecord to never query those columns inspite of the user performing just find without specifying :select
all the time.
use default_scope
e.g.
class MyModel < ActiveRecord::Base
default_scope select("column1, column2, column3")
...
end
Can't you do with a 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">]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With