Skip to main content
Ask A Question
You’re not receiving notifications from this thread.

How do I avoid having duplicate rows in a has_many :through table?

General • Asked by Félix Landry-Audet

I have a Center model and a Department model. The linked :through the Local model. However, I want to avoid inserting the same match twice in the Local table.

Do I use a validate statement or there is a different way of telling Rails to raise an error? What would be the best way?


I got it. I used :

validates_uniqueness_of :center_id, scope: :department_id

Yep, exactly! You can also add an index on that table that includes those two columns in order to speed up the query this validation executes to check validity. That'd be the only other thing you'd probably want to add.

Login or Create An Account to join the conversation.

Subscribe to the newsletter

Join 30,005+ developers who get early access to new screencasts, articles, guides, updates, and more.

    By clicking this button, you agree to the GoRails Terms of Service and Privacy Policy.

    More of a social being? We're also on Twitter and YouTube.