You have a comment form. Someone clicks twice. Oh noes! Double post!
What’s the real problem with double posting? It’s not that the user clicked “submit” several times. The problem is that we have a duplicate record in our database. So instead of fixing this at the view level, we can solve it at the model level in a one-line validation:
class Comment < ActiveRecord::Base belongs_to :post validates_uniqueness_of :body, :scope => [:post_id, :name] end
The above validation acts exactly like a multicolumn database constraint. The order of the fields doesn’t matter, because what gets checked is the uniqueness of the combination of fields (
:name). So if someone wants to comment “cool!” on every post, they can do it, but they can’t comment “cool!” twice on the same post.
Scoping is all the rage right now. But uniqueness scoping is not really related.
show me show me
This solution is implemented here, on Snax. Also, we rolled it into Chow not too long ago. I work on Chow these days. It’s sweet.