ActiveRecord select except columns

后端 未结 4 783
栀梦
栀梦 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: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)
    

提交回复
热议问题