一起使用has_one和belongs_to [英] Using has_one and belongs_to together

查看:48
本文介绍了一起使用has_one和belongs_to的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在同一模型中的同一链接中同时使用has_one和belongs_to是否可以接受?这是它的样子

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

架构如下:

Foo
  name
  special_bar_id

Bar
  name
  foo_id

虽然这与accepts_nested_attributes_for一起使用,但它同时使用has_one和belongs_to来实现此目的.我唯一可以看到的替代方法是在Bar中放置一个is_special_bar字段,该字段的效率较低,因为会有很多空/冗余值.

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.

推荐答案

我相信正确的方法是像您说的那样为Bar创建一个is_special字段:

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

,然后从Foo中删除special_bar_id字段.

这篇关于一起使用has_one和belongs_to的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆