Reputation: 5957
I have two models: ModelA
, ModelB
, related though has_and_belongs_to_many
in both.
Usually, I'd do:
modela.modelbs.create(params)
, but both the models already exist. So, how can I create the relationship in a many-to-many join table (attributes: modela_id
, modelb_id
)?
Essentially giving the SQL: INSERT INGORE INTO join_table (id1, id2);
(IGNORE
is important here as I have a unique index on (modela_id, modelb_id)
Upvotes: 1
Views: 159
Reputation: 5957
To achieve what I set out and avoid extra logic and database queries, https://github.com/zdennis/activerecord-import works brilliantly and with :ignore => true
provides INSERT INGORE
Upvotes: 0
Reputation: 19899
modela.modelbs << modelb
See the has_and_belongs_to_many api docs for more info.
Upvotes: 1