我有两个类:Schedule
和Interaction
,他们看起来如下:质量分配OBJECT_ID对象
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
有人可以告诉我为什么这是,我怎么可以解决它?
感谢您的回答!
首先,你应该有'belongs_to:schedule'的交互,否则外键不会被保存。修复模型文件中的错误后,再试一次,虽然我不知道这是否会起作用。 – Zippie
谢谢!我已经试过这个,它不能解决问题。此外,互动确实不属于时间表,所以我认为has_one是正确的。我认为当你使用belongs_to关联时,关键是自动生成的,has_one必须手动生成,但它仍然有效afaik – Zois
你不能拥有一个拥有多个关系。外键不会被保存在任何地方。 – Zippie