gpt4 book ai didi

mysql - 如何使用 ruby​​ on Rails 为 ActiveRecord 关联添加唯一性

转载 作者:行者123 更新时间:2023-11-30 00:43:59 26 4
gpt4 key购买 nike

我有一个博客应用程序,用户可以在其中发布文章,其他用户可以对文章发表评论,并且可以对评论进行投票。在任何投票系统上,用户对评论进行一次投票,如果愿意,可以对帖子上的所有评论进行投票。但在这一点上,我希望限制用户对一篇文章的一个评论只能投一票,这样评论就可以根据用户投票进行排名。因此,唯一性验证会检查用户是否对文章的评论进行了投票。

class User < ActiveRecord::Base 
has_many :articles
end

class Article < ActiveRecord::Base
belongs_to :user
has_many :comments
end

class Comment< ActiveRecord::Base
belongs_to :article
has_many :votes
end

class Vote< ActiveRecord::Base
belongs_to :comment
belongs_to :post
end

最佳答案

进行此更改(我认为这是您的输入错误)

class CommentPost< ActiveRecord::Base 
belongs_to :comment
belongs_to :post
end

创建迁移以添加索引

add_index :comment_post, [:comment_id, :post_id], unique: true

同样的投票使用索引

关于mysql - 如何使用 ruby​​ on Rails 为 ActiveRecord 关联添加唯一性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21544713/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com