1

我有两个类:Schedule它们Interaction看起来如下:

class Schedule < ActiveRecord::Base
  has_many :interactions

end

class Interaction < ActiveRecord::Base
  attr_accessible :schedule_id

  has_one :schedule

end

迁移如下所示:

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

当我这样做时:

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

Interaction_high_1获取指定的schedule_id,其余的只是nul

谁能告诉我为什么会这样以及我该如何解决?

谢谢你的回答!!

4

1 回答 1

2

您正在创建交互而不将它们与计划相关联。稍后仅附加它们不会满足您的需要。改为这样做:

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

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

此外,:has_one将交互模型中的 更改为:belongs_to.

于 2013-04-02T17:15:12.323 回答