Using has_one and belongs_to together

家住魔仙堡 提交于 2019-12-24 09:56:53

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/7392434/using-has-one-and-belongs-to-together

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!