我有一个带有两个表的评论系统:评论和用户。在评论中我想记录作者是谁,我也想通过(@username)通知评论中提到的任何用户。所以我认为我需要在评论上有一个author_id,还有一个带有评论ID和所有用户ID的comments_users表。这是完成它的正确方法吗?:
用户:
has_many :comments
注释:
belongs_to :users, class_name: 'User', foreign_key: 'author_id'
has_many :users
答案 0 :(得分:3)
可以建立协会:
#app/models/user.rb
Class User < ActiveRecord::Base
has_many :comments
has_and_belongs_to_many :mentions, join_table: "comments_users", association_foriegn_key: "comment_id"
end
Class Comment < ActiveRecord::Base
belongs_to :author, class_name: "User", foreign_key: "author_id"
has_and_belongs_to_many :mentions, join_table: "comments_users", foreign_key: "comment_id"
end
#comments_users
comment_id | user_id
这将允许您致电:
@user.comments #-> shows comments user has authored
@user.mentions.first.comment #-> shows first comment user was mentioned in
@comment.author #-> shows user who authored comment
@comment.mentions.first.user #-> shows first user who was mentioned in comment
<强>更新强>
HABTM仍然需要一个表(Rails migration for has_and_belongs_to_many join table),但区别在于它不需要主键列(仅comment_id | user_id
)
我们创建了一种“自我引用”的habtm关系,这意味着您不需要“创建”任何记录 - 它们都应该已经创建。 HABTM将仅引用它们。因此,您需要use the <<
ActiveRecord method将记录添加到mentions
集合中:
#app/controllers/comments_controller.rb
Class CommentsController < ActiveRecord::Base
def create
@comment = Comment.new(comments_params)
@comment.save_with_mentions
end
end
#app/models/comment.rb
Class Comment < ActiveRecord::Base
def save_with_mentions
comment = self.save
#do something to find mentioned users
mentioned_users = User.where("user_id = 1") #example
for user in mentioned_users do
comment.mentions << user
end
end
end
答案 1 :(得分:1)
总有很多方法可以完成任何给定的任务,但我猜测你正在为你的模型寻找类似的东西。关联。
用户:
has_many :comments
用户模型关联看起来正确。
注释:
belongs_to :author, class_name: 'User', foreign_key: 'user_id'
has_many :users
注意,belongs_to应该以单数命名方式引用模型(即:用户与用户)。我想你会想要像comments.author这样的参考来找到你评论的作者。更常见的是,在引用用户模型时提供user_id的foreign_key以保持清晰,但随后提供澄清的关联名称,如&#34; author&#34;或者&#34;创作者&#34;或者我在上面展示的任何参考资料。因此,您的Comments表将有一个foreign_key的user_id,以引用回Users表。该用户将在Rails中通过名称&#34; author&#34;。
引用问题的第二部分与跟踪模型中的其他用户引用有关,听起来像是comment-users表中的一对多。所以,这听起来像一个选项。与你的&#34;作者&#34;相似评论,您可能希望提供更清晰的名称,如&#34;标签&#34;这可以只是对用户的引用。 如果您计划在应用程序的其他位置使用此原则(例如用于引用/标记其他元素(如照片或发布内容)中的人员),此功能的另一个好选择可能是设置多态表(基本上是灵活的连接表) 。它可以为添加功能和跟踪这些用户参考提供更大的灵活性。多态表可以有任何名称,但通常有一个&#34; -able&#34;类型名称 - 像&#34; taggable&#34;。这是一个有用的参考:http://guides.rubyonrails.org/association_basics.html#polymorphic-associations