Using has_one and belongs_to together

2019-07-30 01:20发布

问题:

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.