Restrict the columns represented in ActiveRecord

坚强是说给别人听的谎言 提交于 2019-12-23 08:28:14

问题


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.


回答1:


use default_scope

e.g.

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

  ...
end



回答2:


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">] 


来源:https://stackoverflow.com/questions/8758455/restrict-the-columns-represented-in-activerecord

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!