简体   繁体   中英

Mass assign object_id to objects

I have two classes: Schedule and Interaction and they look the following:

class Schedule < ActiveRecord::Base
  has_many :interactions

end

class Interaction < ActiveRecord::Base
  attr_accessible :schedule_id

  has_one :schedule

end

The migrations look like this:

class CreateSchedules < ActiveRecord::Migration
  def change
    create_table :schedules do |t|
      t.timestamps

    end
  end
end


class CreateInteractions < ActiveRecord::Migration
  def change
    create_table :interactions do |t|
      t.integer :schedule_id

      t.timestamps
    end
  end
end

When I do this:

irb(main):003:0> interaction_high_1 = Interaction.create()
irb(main):003:0> interaction_high_2 = Interaction.create()
irb(main):003:0> interaction_high_3 = Interaction.create()
irb(main):003:0> interaction_high_4 = Interaction.create()
irb(main):003:0> interaction_high_5 = Interaction.create()

irb(main):003:0> schedule1 = Schedule.create(:name => "high1").interactions << interaction_high_1, interaction_high_2, interaction_high_3, interaction_high_4, interaction_high_5

only Interaction_high_1 gets the designated schedule_id and for the rest it's just nul

Can anybody tell me why this is and how I might fix it?

Thanks for an answer!!

You are creating the Interactions without associating them to a Schedule. Just appending them later won't do what you need. Do it like this instead:

schedule1 = Schedule.create(:name => "high1")

1...5.times do
  schedule1.interactions.create
end

Also, change the :has_one in the Interaction model to a :belongs_to .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM