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

Ask A Question

Notifications

You’re not receiving notifications from this thread.

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

Félix Landry-Audet asked in General

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?

Thanks,

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.

Join the discussion

Want to stay up-to-date with Ruby on Rails?

Join 38,558+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.

    logo Created with Sketch.

    Ruby on Rails tutorials, guides, and screencasts for web developers learning Ruby, Rails, Javascript, Turbolinks, Stimulus.js, Vue.js, and more. Icons by Icons8

    © 2020 GoRails, LLC. All rights reserved.