我确定这是一个非常简单的问题,但我只是个新手,所以...
我有一个模型 Game,它 has_many :piles
。依次堆放 has_many :cards
。我可以在创建游戏时填充桩和纸牌,所以我目前的代码看起来像:
class Game < ActiveRecord::Base
has_many :piles
def after_create
1.upto(4) do |num|
Pile.new("game_id" => id, "contents" => "c_type_#{num}")
end
end
end
class Pile < ActiveRecord::Base
has_many :cards
belongs_to :game
def after_create
1.upto(10) do |num|
Card.new("pile_id" => id, "value" => num)
end
end
end
class Card < ActiveRecord::Base
belongs_to :pile
end
现在一切都很好,但是当 ActiveRecord 知道 game_id 是外键并且应该引用时传递 "game_id"=> id
感觉不对家长游戏。但是,如果我将其关闭,外键最终将无法设置。有更好的方法吗?
(作为奖励,可能更简单,问题;假设 Game 也 has_one :monkey
。如何最好地从 Game 模型中创建猴子?)
最佳答案
代替:
Pile.new("game_id" => id, "contents" => "c_type_#{num}")
尝试:
piles.create("contents" => "c_type_#{num}")
它会尝试立即保存创建的堆。或者,如果您确实需要不进行任何保存(create
就是这种情况),您可以:
new_pile = piles.build("contents" => "c_type_#{num}")
类似于 Pile 类及其卡片。
对于 has_one :monkey
,您可以执行以下操作(在 Game 的方法中):
create_monkey("some_attr" => "some_value")
关于ruby-on-rails - ruby rails : Creating child objects,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2038238/