这是我在 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_id
和 post_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/