Do all join tables have tables?

For example, I have comment models, and I have a publication model, but comments can comment on other comments.

I think I need a connection table, which I will name commentables. To create this, do I really need to create a noteworthy table with post_id and comment_id?

Or I can do something like this without it:

has_many            :comments,
                    :through => :commentables,
                    :source => :post

Not sure which is the best way to do this. I am a huge newbie.

+3
source share
1 answer

, . has_and_belongs_to_many, ( , ?).

. :

class Post < ActiveRecord::Base
  has_many :comments, :as => :parent
end

class Comment < ActiveRecord::Base
  belongs_to :parent, :polymorphic => true
  has_many   :children, :class_name => 'Comment', :as => :parent # We need to point this relationship to the Comment model, otherwise Rails will look for a 'Child' model
end

, . Comment.last.parent Post, Comment.

, , :

class Post < ActiveRecord::Base
  has_many :comments
end

class Comment < ActiveRecord::Base
  belongs_to :post
  belongs_to :parent, :class_name => 'Comment'   # We need to point this relationship to the Comment model, otherwise Rails will look for a 'Parent' model
  has_many   :children, :class_name => 'Comment' # We need to point this relationship to the Comment model, otherwise Rails will look for a 'Child' model
end

, , .

( , ), . ( , ), . .

+5

Source: https://habr.com/ru/post/1769460/


All Articles