Search code examples
mysqlruby-on-railsrubyactiverecordvoting

how to add uniqueness to ActiveRecord association using ruby on rails


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

Solution

  • 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