Understanding Rails ActiveRecord “single model” self joins

后端 未结 1 1773
清歌不尽
清歌不尽 2021-01-31 06:12

I\'m having a hard time understanding how to implement a single model self-join in Rails. The Guide to ActiveRecord Associations section 2.10 briefly explains Self-Joins but do

相关标签:
1条回答
  • 2021-01-31 06:33

    I was missing the has_many foreign key to "parent_post_id". Once its set, the post.replies will reference other Post instances by parent_post_id.

    The posts.rb model has the relationship defined:

    class Post < ActiveRecord::Base
      has_many :replies, :class_name => "Post",
        :foreign_key => "parent_post_id"
      belongs_to :parent_post, :class_name => "Post",
        :foreign_key => "parent_post_id"
    end
    

    I can now create Posts, assign a parent_post_id to a different Post, then later get all Posts that are replies to any parent Post.

    0 讨论(0)
提交回复
热议问题