2011-09-12 41 views
1

將has_one和belongs_to同時用於同一模型中的同一鏈接可以接受嗎?下面是它的外觀將has_one和belongs_to一起使用

Class Foo 
    has_many :bars 
    has_one :special_bar, :class_name => "Bar" 
    accepts_nested_attributes_for :special_bar, :allow_destroy => true 
    belongs_to :special_bar, class_name => "Bar" 
end 

Class Bar 
    belongs_to :foo 
end 

的模式如下:

Foo 
    name 
    special_bar_id 

Bar 
    name 
    foo_id 

雖然這與accepts_nested_attributes_for,它同時使用HAS_ONE和belongs_to的工作來實現這一目標。我能看到的唯一選擇是在Bar中放入一個is_special_bar字段,由於會有大量的空值/冗餘值,效率會降低。

回答

2

我認爲正確的方法是有一個is_special領域Bar像你說:

Class Foo 
    has_many :bars 
    has_one :special_bar, :class_name => "Bar", :conditions => ['is_special = ?', true] 
    accepts_nested_attributes_for :special_bar, :allow_destroy => true 
end 

Class Bar 
    belongs_to :foo 
end 

,並從Foo刪除special_bar_id領域。

+0

這就是我猜到的。感謝您的確認:D – hash12