Ruby on rails 所有联接表都有表吗?
例如,我有一个评论模型,我有一个帖子模型,但是评论可以对其他评论进行评论 因此,我似乎需要一个连接表,我将调用Ruby on rails 所有联接表都有表吗?,ruby-on-rails,ruby,ruby-on-rails-3,join,Ruby On Rails,Ruby,Ruby On Rails 3,Join,例如,我有一个评论模型,我有一个帖子模型,但是评论可以对其他评论进行评论 因此,我似乎需要一个连接表,我将调用commentables。要创建这个,我真的需要创建一个带有post\u id和comment\u id的可注释表吗 或者我可以在没有这个的情况下做这样的事情: has_many :comments, :through => :commentables, :source =>
commentables
。要创建这个,我真的需要创建一个带有post\u id和comment\u id的可注释表吗
或者我可以在没有这个的情况下做这样的事情:
has_many :comments,
:through => :commentables,
:source => :post
我真的不确定实现这一目标的最佳方式是什么。我是一个超级新手。不,在这种情况下,不应该需要连接表。联接表用于
具有且属于多个关系,在这种情况下,您不需要拥有其中一个(注释不能属于多个帖子,对吗?)
你有两个选择。第一个是创建多态关系:
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
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
这样,你的评论将永远属于一篇文章,也可能属于另一篇评论
如果您计划嵌套注释(至少不止一个级别),我建议第二个选项。这将允许您在一个查询中获取特定帖子的所有评论(而不必为每个评论查找子评论),并且您可以在呈现评论之前在应用程序中对评论进行排序。但是任何一种方法都应该有效。嘿,Voncorad,我很好奇你是否知道如何设置此表单?我一直在努力解决这个问题: