ActiveRecord includes. Specify included columns

后端 未结 6 464
野的像风
野的像风 2020-12-02 17:08

I have model Profile. Profile has_one User. User model has field email. When I call

Profile.some_scope.includes(:user)

it calls

<         


        
6条回答
  •  难免孤独
    2020-12-02 17:38

    I wanted that functionality myself,so please use it. Include this method in your class

    #ACCEPTS args in string format "ASSOCIATION_NAME:COLUMN_NAME-COLUMN_NAME"

    def self.includes_with_select(*m)
        association_arr = []
        m.each do |part|
          parts = part.split(':')
          association = parts[0].to_sym
          select_columns = parts[1].split('-')
          association_macro = (self.reflect_on_association(association).macro)
          association_arr << association.to_sym
          class_name = self.reflect_on_association(association).class_name 
          self.send(association_macro, association, -> {select *select_columns}, class_name: "#{class_name.to_sym}")
        end
        self.includes(*association_arr)
      end
    

    And you will be able to call like: Contract.includes_with_select('user:id-name-status', 'confirmation:confirmed-id'), and it will select those specified columns.

提交回复
热议问题