一起使用has_one和belongs_to

时间:2011-09-12 18:47:35

标签: ruby-on-rails nested-attributes

对于同一模型中的同一链接,同时使用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,但它使用BOTH has_one和belongs_to来实现此目的。我能看到的唯一选择是在Bar中放置一个is_special_bar字段,效率较低,因为会有很多空/冗余值。

1 个答案:

答案 0 :(得分: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

并从special_bar_id中删除Foo字段。