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.