ActiveRecord select except columns

喜欢而已 提交于 2019-12-18 02:12:28

问题


Is there a way I can specify to select ALL columns in ActiveRecord except just a few. For example, for a User, I don't want to select their password hash or their email. Is this possible or do I have to manually hardcode all columns?

Thanks


回答1:


write a scope like

def select_without columns
  select(column_names - columns.map(&:to_s))
end



回答2:


Something like this?

exclude_columns = ['password', 'email']
columns = User.attribute_names.delete_if(|x| exclude_columns.include?(x))

User.select(columns)

EDIT

I forgot that we can do Array1 - Array2

A best answer:

exclude_columns = ['password', 'email']
columns = User.attribute_names - exclude_columns

User.select(columns)



回答3:


Another really usefull way it's with a scope inside the model in case you need to avoid a column constantly.

In my case I save images into blob fields so I whant to avoid those to be loaded everytime and in a easy way:

scope :select_exclude_image, ->  { select( Movie.attribute_names - ['image'] ) }

Then to avoid the image in the selection you can do something like that:

Movie.select_exclude_image.first

or

Movie.select_exclude_image.all

I hope it will help!



来源:https://stackoverflow.com/questions/17431028/activerecord-select-except-columns

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