In the typical rails (4.2.x) blog app, I have a Post model. The post has a boolean column called primary. I want to enforce a model level constraint that at most one post has primary=true. If user sets a new post to be primary=true, all other posts must be marked primary=false before saving this post.
I could do this in the controller, when a post is created or updated to be primary=true, by changing all other posts to primary=false. Something like:
# in posts_controller#create and #update
...
if @post.primary
[Post.all - self].select(&:primary).each do {|p|p.primary = false; p.save}
end
@post.save!
...
However, I want this to be a model level constraint, so I can add validations, unit tests, etc. that there is only one post with primary=true. If I use a callback like before_commit, then I may run into an infinite loop since updating the older posts in a new post's before_commit will trigger the older posts' before_commit, etc.
How do I enforce this behavior at the model level?