I have a polymorphic table called "Votes", where has votes from Answers and Questions.
Votes
user_id voteable_id voteable_type value
1 2 Answer 1
2 2 Answer 1
In this case, the answer with id = 2 has two votes up.
The question is: How to index this table?
First approach:
add_index :votes, [:voteable_id, :voteable_type]
This will not work because duplicate key value will violates unique constraint
Second approach:
add_index :votes, :voteable_id,
add_index :votes, :voteable_type
This one I guess will not have much performance because of the composite queries for id and type at the same time.
Third approach:
add_index :votes, [:user_id, :voteable_id, :voteable_type]
Is this last one a good one? Are three columns to be indexed too much?
Thanks
your first approach is the right one
add_index :votes, [:voteable_id, :voteable_type]
as long as you don't add :unique => true
it will not be unique. And you shouldn’t make it unique, as this would result in only one vote per votable would be possible. As Tashos states in the comments.
The third approach would work too, and here you can use a unique
constraint, so every user can only vote once per votable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With