You need to have a way to insure unique ID’s in your primary key attributes. The easiest way since you are using some sort of SQL is to use the auto increment feature on your primary key fields.
Edit: this isn’t a good solution for this issue. I didn’t read the whole problem and just the dB error. Sorry for any confusion.
I’d figure out why you’re getting duplicate entries in the first place. Since this error shouldn’t really ever happen I’d use a try catch like you are. Since you mentioned performance is key I’d limit the active query usage and manually do the linking.
ActiveRecord::link() involving a junction table could be a little tricky, since it doesn’t check the already existing record before inserting the link record by design.
I usually do something like the following:
$show = ... // the show in focus
$persons = [...]; // selected persons
$show->unlinkAll('persons', true);
foreach($persons as $p) {
$show->link('persons', $p);
}
Since I tend to use a list box with multiple selection (which holds the selected ids) for handling this kind of relation, the code above works nice for me.
that is design choice by wrapping it in a try/catch if it blows you run a query again, indirectly also related to performance. Another solution could be don’t make your column(s) to be primary keys just add simple index on both columns and keep inserting you don’t need the try/catch and later on you may run a cron job that cleans your table and removes the dups.