rails select and include

前端 未结 5 1305
清歌不尽
清歌不尽 2021-02-19 02:02

Can anyone explain this?

Project.includes([:user, :company])

This executes 3 queries, one to fetch projects, one to fetch users for those proje

5条回答
  •  囚心锁ツ
    2021-02-19 02:23

    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.

提交回复
热议问题