Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Restrict the columns represented in ActiveRecord

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.

like image 739
jVenki Avatar asked Jan 06 '12 13:01

jVenki


2 Answers

use default_scope

e.g.

class MyModel < ActiveRecord::Base
  default_scope select("column1, column2, column3")

  ...
end
like image 64
Chris Bailey Avatar answered Sep 21 '22 19:09

Chris Bailey


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">] 
like image 42
Syed Aslam Avatar answered Sep 19 '22 19:09

Syed Aslam