ActiveRecord select except columns

后端 未结 4 779
栀梦
栀梦 2020-12-15 06:54

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

相关标签:
4条回答
  • 2020-12-15 07:22

    In some cases, particularly when you're considering a default_scope to exclude certain columns, I would advise against this approach because of a known issue with Rails about count breaking after a select clause. This can lead to surprising downstream errors.

    In such a case, consider instead breaking your record into two tables, one with the essential data, the other one with the data you only need from time-to-time, then use associations to access the extra data.

    0 讨论(0)
  • 2020-12-15 07:29

    write a scope like

    def select_without columns
      select(column_names - columns.map(&:to_s))
    end
    
    0 讨论(0)
  • 2020-12-15 07:31

    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 want 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!

    0 讨论(0)
  • 2020-12-15 07:33

    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)
    
    0 讨论(0)
提交回复
热议问题