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,

Reply

I got it. I used :

validates_uniqueness_of :center_id, scope: :department_id

Reply

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.

Reply

Thanks Chris!

Reply
Join the discussion
Create an account Log in

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

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

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