Eager Load Depending on Type of Association in Ruby on Rails

后端 未结 7 2344
温柔的废话
温柔的废话 2021-02-07 22:13

I have a polymorphic association (belongs_to :resource, polymorphic: true) where resource can be a variety of different models. To simplify the questio

7条回答
  •  北恋
    北恋 (楼主)
    2021-02-07 22:21

    I would like to share one of my query that i have used for conditional eager loading but not sure if this might help you, which i am not sure but its worth a try.

    i have an address model, which is polymorphic to user and property. So i just check the addressable_type manually and then call the appropriate query as shown below:-

    after getting either user or property,i get the address to with eager loading required models

    ##@record can be user or property instance
    if @record.class.to_s == "Property"
         Address.includes(:addressable=>[:dealers,:property_groups,:details]).where(:addressable_type=>"Property").joins(:property).where(properties:{:status=>"active"})
    else if @record.class.to_s == "User"
         Address.includes(:addressable=>[:pictures,:friends,:ratings,:interests]).where(:addressable_type=>"User").joins(:user).where(users:{is_guest:=>true})
    end
    

    The above query is a small snippet of actual query, but you can get an idea about how to use it for eager loading using joins because its a polymorphic table.

    Hope it helps.

提交回复
热议问题