[英]Mass assign object_id to objects
I have two classes: Schedule
and Interaction
and they look the following: 我有两个类: Schedule
和Interaction
,它们看起来如下:
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 只有Interaction_high_1
获得指定的schedule_id ,其余的只是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
. 另外,将交互模型中的:has_one
更改为:belongs_to
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.