Вопрос

I have a blog application where users can post article, other users can comment on the article and comments can be voted on. On any voting system users vote once on comment and can vote on all the comments on a post if the want to. But on this one I want limit users to one vote for one comment on an article so comments can be ranked based on user vote. So the uniqueness validation checks if user has voted on an article's comment.

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
Это было полезно?

Решение

do this changes (i think its your typing error)

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

create a migration to add index

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

same for votes use the index

Другие советы

Based on your explanation of the problem, and seeing some of the comments left by others, I believe the code block you intended to provide was something more like this:

class User < ActiveRecord::Base 
     has_many :articles
     has_many :votes
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 :user
end

A vote is associated with a comment and with a user. But you want to ensure that a user can only vote on any given comment one time. To do this, you can modify the Vote class by adding a validation line:

class Vote< ActiveRecord::Base 
     belongs_to :comment
     belongs_to :user

     validates :user, uniqueness: { scope: :comment,
                                    message: "User can only vote on this comment one time" }
end

To explain the above... You add a line to validate a user's uniqueness for a vote. But, if you do not narrow the scope of the uniqueness, then what you would be saying is that a user can only vote one time (across your entire system). When you specify the scope of a user's uniqueness to be a :comment, then you are saying that a user can only vote one time per comment.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top