将object_id分配给对象

时间:2013-04-02 17:08:00

标签: ruby-on-rails ruby sqlite

我有两个类:ScheduleInteraction,它们看起来如下:

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

有人可以告诉我为什么会这样,以及如何解决它?

感谢您的回答!

1 个答案:

答案 0 :(得分:2)

您正在创建交互,而不将它们与计划相关联。稍后添加它们将无法满足您的需求。这样做是这样的:

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

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

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