Eager loading of polymorphic associations in ActiveRecord

后端 未结 3 767
日久生厌
日久生厌 2021-02-06 11:48

This is my first time using Rails and I was wondering if it\'s possible to load a has one polymorphic association in one SQL query? The models and associations between them are

3条回答
  •  挽巷
    挽巷 (楼主)
    2021-02-06 12:45

    After digging through the Rails source I've discovered that you can force a join by referencing a table other than the current model in either the select, conditions or order clauses.

    So, if I specify an order on the Asset table:

    Image.first(
          :conditions => {:id => id},
          :include => :asset,
          :order => "asset.id"
    )
    

    The resulting SQL will use a left outer join and everything in one statement. I would have preferred an inner join, but I guess this will do for now.

提交回复
热议问题