STI and polymorphs

前端 未结 5 1354
孤独总比滥情好
孤独总比滥情好 2021-01-04 13:53

I have problem with my code

class Post < ActiveRecord::Base
end

class NewsArticle < Post
  has_many :comments, :as => :commentable, :dependent =>         


        
5条回答
  •  不知归路
    2021-01-04 14:36

    Take a look at the Polymorphic Associations section of ActiveRecord::Associations API. There is a little bit about using polymorphic associations in combination with single table inheritance. Following the second code example in that section I think this might be close to what you want

    class Comment < ActiveRecord::Base
      belongs_to :commentable, :polymorphic => true, :counter_cache => true
    
      def commentable_type=(sType)
       super(sType.to_s.classify.constantize.base_class.to_s)
      end
    end
    
    class Post < ActiveRecord::Base
      has_many :comments, :as => :commentable, :dependent => :destroy, :order => 'created_at'
    end
    
    class NewsArticle < Post
    end
    

提交回复
热议问题