ruby-on-rails - Ruby on Rails : How to iterate whether the user already commented on the post

标签 ruby-on-rails ruby

这是我在 stackoverflow 中的第一个问题,所以请耐心等待,呵呵。

我有三个模型:用户、帖子和评论。

# user.rb
class User < ApplicationRecord
  has_many :posts
  has_many :comments
end

# post.rb
class Post < ApplicationRecord
  belongs_to :user
  has_many :comments
end

# comments.rb
class Comment < ApplicationRecord
  belongs_to :user
  belongs_to :post
end

我想要实现的是让用户在帖子中只评论一次。如果同一用户已存在评论,则不应接受保存/创建。

到目前为止,我的想法是创建一个模型函数,它迭代所有现有的 post.comments.each 然后检查所有用户,如果有,则评论无效。虽然我不知道该怎么做。

如果您有任何想法(也许还有代码片段),请分享。提前致谢! :)

最佳答案

在您的comment.rb

validates :user_id, uniqueness: { scope: [:post_id]}

此验证将确保 user_idpost_id 组合在您的 comments 表中是唯一的。

关于ruby-on-rails - Ruby on Rails : How to iterate whether the user already commented on the post,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42018152/

相关文章:

ruby-on-rails - ActiveModel 禁止属性错误

Ruby:将方法添加到输入参数的类中

ruby-on-rails - 图像未删除 Carrierwave

ruby-on-rails - 检索顶级 namespace Ruby

ruby-on-rails - 当我尝试安装 mysql2 (OSX) 时,出现 "failed to build gem native extension."

ruby-on-rails - Rails - 排序依据,使用 grouped_collection_select

ruby-on-rails - 检测 Rails 是否正在运行站点

mysql - 将 AR 模型与临时表连接起来

ruby-on-rails - 尽管模板存在,但 Rails 持久性 "No template for interactive request"

ruby-on-rails - 在 Rails 中显示未读帖子