我很難搞清楚如何最好地建模我的數據。我有以下兩種模式在我的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