2011-09-12 44 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