我很难搞清楚如何最好地建模我的数据。我有以下两种模式在我的Rails应用程序:Rails/ActiveRecord:has_one,belongs_to和before_create
class Foo < ActiveRecord::Base
belongs_to :active_bar, :class_name => 'Bar'
accepts_nested_attributes_for :active_bar
before_create do |f|
f.active_bar.foo = f
# Causes stack overflow!
f.active_bar.save!
end
end
class Bar < ActiveRecord::Base
belongs_to :foo
end
test 'create with nested attributes' do
f = Foo.create!(:name => 'foo-name', :active_bar_attributes => {:name => 'bar-name'})
assert_equal 'foo-name', f.name
assert_equal 'bar-name', f.active_bar.name
assert_equal f, f.active_bar.foo
f_id = f.to_param
retrieved_f = Foo.find_by_id!(f_id)
assert_equal retrieved_f, retrieved_f.active_bar.foo
end
什么你可能觉得很奇怪是自反belongs_to
关系,我试图建模。我的计划是,最终,Foo
将有许多Bar
的实例,而一个实例将被视为“活动”。因此,我使用active_bar
来引用此活动实例。此代码的问题是,我需要将Bar
中的foo
属性设置回父代Foo
实例,我无法弄清楚最好的做法(save!
调用before_create
最终会递归并溢出堆栈)或者即使这是对这种类型的关系建模的最干净的方式。
本质上我试图模拟一个用户(相当于Foo
)谁拥有多个电子邮件地址(相当于Bar
)与其中一个电子邮件地址标记为用户的主要地址。
有什么建议吗?
我想我会将'before_create'中的代码移动到'after_create'中代替。这似乎工作。然而,我仍然不完全满意于模拟的关系。 – 2010-07-16 18:10:51