2013-04-02 59 views
1

我有两个类:ScheduleInteraction,他们看起来如下:质量分配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

有人可以告诉我为什么这是,我怎么可以解决它?

感谢您的回答!

+1

首先,你应该有'belongs_to:schedule'的交互,否则外键不会被保存。修复模型文件中的错误后,再试一次,虽然我不知道这是否会起作用。 – Zippie

+0

谢谢!我已经试过这个,它不能解决问题。此外,互动确实不属于时间表,所以我认为has_one是正确的。我认为当你使用belongs_to关联时,关键是自动生成的,has_one必须手动生成,但它仍然有效afaik – Zois

+0

你不能拥有一个拥有多个关系。外键不会被保存在任何地方。 – Zippie

回答

3

您正在创建交互而不将它们关联到计划。稍后追加它们将不会满足您的需求。像这样做,而不是:

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

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

此外,在互动模型的:belongs_to改变:has_one

+0

谢谢!!这工作 - 你有什么想法,为什么在我的例子中,第一个对象获得了关键,但其余的不是? 至于:has_one和:belongs_to看到上面的评论 – Zois

+2

belongs_to必须在那里。这不值得怀疑。我敢打赌,你现在拥有它的方式,像'interation1.schedule'这样的东西会引发一个错误。 – messick

+0

至于只有第一次获得关键的交互:Rails以神秘的方式工作,特别是当你做错了什么。这不会是最后一次你会看到Rails做一些奇怪的事情,而不是当你犯了一个错误,只是吹起来。 – messick