Reputation: 93
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.
Upvotes: 7
Views: 1002
Reputation: 8807
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">]
Upvotes: 2
Reputation: 4136
use default_scope
e.g.
class MyModel < ActiveRecord::Base
default_scope select("column1, column2, column3")
...
end
Upvotes: 10