Rails: includes with polymorphic association

前端 未结 6 652
暗喜
暗喜 2020-12-24 11:55

I read this interesting article about Using Polymorphism to Make a Better Activity Feed in Rails.

We end up with something like

class Activity < A         


        
6条回答
  •  醉梦人生
    2020-12-24 12:17

    I would suggest adding the polymorphic association to your Event and Guest models. polymorphic doc

    class Event < ActiveRecord::Base
      has_many :guests
      has_many :subjects
      after_create :create_activities
    end
    
    class Image < ActiveRecord::Base
      has_many :tags
      has_many :subjects
      after_create :create_activities
    end
    

    and then try doing

    Activity.includes(:subject => [:event, :guest]).order(created_at: :desc).limit(20)
    

提交回复
热议问题