STI and polymorphs

前端 未结 5 1378
孤独总比滥情好
孤独总比滥情好 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:17

    The commentable_type field needs to store the name of the table that contains the data, once that row is loaded from the right table, the inherited type will be loaded from the type column on the Posts table.

    So:

    Here the comment points to the table that it comments on. The posts table, id 1

    >> Comment.first
    => #
    

    Then to load the NewsArticle, id 1 is loaded from posts, and the type there indicates a NewsArticle.

    >> Comment.first.commentable
    => #
    >> Comment.first.commentable.class.table_name
    => "posts"
    

    If commentable_type held "NewsArticle" it would have to look at the class to determine the table. This way it can just look to the table and worry about the type once it gets there.

提交回复
热议问题