Search code examples
activerecordruby-on-rails-3.2padrino

Rails 3 insert data into junction table automatically


I would have thought that if a table relationship is set up properly in a model file, ActiveRecord would take care of updating and inserting the data into the junction table.

Is this not so?

For example, I have a dvd.rb model that looks like this:

  has_and_belongs_to_many :dvd_producer

The junction table is named accordingly dvd_producers_dvds (I know, silly name but that's what ActiveRecord expects).

Basically, when I insert a new producer into the dvd_producers table via:

DvdProducer.create(producer: producer)

I would expect that ActiveRecord inserts the equivalent data (producer_id, dvd_id) into the junction table automatically.

Maybe I need to use the new_producer.save method instead of create?

Or is this just a pipe dream?


Solution

  • Are you ever appending a dvd to the dvd_producer? I'm not even seeing you create a dvd, something like.

    producer = DvdProducer.create(producer: producer)
    producer.dvds << Dvd.create(title: title)
    

    Should get you what you want.