[英]rails how many foreign keys a table should have
我有一个rails4应用程序。 我有下面的架构,将增加post_replies
表,将belong_to :post_comment
和post_comment
将has_many :post_replies
。 评论中的回复将始终属于给定的评论。
我的问题是应该在post_replies中添加多少外键? 我将始终只在post index page
上显示它们,并且将使用format_js
添加新的回复。 post_reply
belongs_to post_comment
post_reply
肯定,但是我也应该同时使用belongs_to :user
和belongs_to :post
?
当前架构:
class User < ActiveRecord::Base
has_many :posts
has_many :post_comments, through: :posts
end
class Post < ActiveRecord::Base
has_many :post_comments
belongs_to :user
end
class PostComment < ActiveRecord::Base
belongs_to :post
belongs_to :user
end
计划架构:
class PostReply < ActiveRecord::Base
belongs_to :post_comment #this is needed for sure
belongs_to :post #do i need this?
belongs_To :user #and this?
end
路线:
#current:
resources :posts do
resources :post_comments, only: [:create, :update, :destroy], module: :posts
end
#and planning to add:
resources :post_comments, only: [] do
resources :post_repiles, only: [:create, :update, :destroy], module: :posts
end
它应该属于User但如果它已经属于post_comment则不需要属于该帖子,因为您可以通过该模型访问post。
我想你应该命名PostReply
CommentReply
,因为它是直接对评论的回覆,而不是职位。
如果您已经有评论ID,则不需要保存post_id,因为评论已经与帖子有关系。
这应该工作得很好。
class CommentReply < ActiveRecord::Base
belongs_to :post_comment
belongs_To :user
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.