开发者

Using has_one and belongs_to together

Is it acceptable to use both has_one and belongs_to for the same link in the same model? Here is how it looks

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

The schema is as follows:

Foo
  name
  special_bar_id

Bar
  name
  foo_id

While this works with the accepts_nested_attributes_for, its using BOTH has_one and belongs_to to achieve this. The only alternative I can see is putting an is_special_bar field in Bar, which would be less efficient since there would be a lot of empty/redundant values开发者_开发知识库.


I believe the proper way would be to have an is_special field for Bar like you said:

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

and remove the special_bar_id field from Foo.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜