有关空的belongs_to关联的最佳实践 [英] Best practice about empty belongs_to association
问题描述
想象一下以下情况:
我有一个狗
模型和一个房子
模型。狗可以属于一个房子,而一个房子可以有很多狗,因此:
I have a dog
model and a house
model. A dog can belong to a house, and a house can have many dogs, so:
Class Dog < ActiveRecord::Base
belongs_to :house
end
Class House < ActiveRecord::Base
has_many :dogs
end
现在,想象一下我也想创造没有房子的狗。他们不属于房屋。我仍然可以使用这种关系结构,而在创建它时不通知:house_id
吗?
Now, imagine that I also want to create dogs that don't have a house. They don't belong to house. Can I still use that relationship structure and simply don't inform a :house_id
when creating it?
更好的做法?
Obs .:我用这种类比简化了我的问题,但是我的实际情况是:我有一个模型,用户可以生成它的实例。他还可以创建这些实例的集合,但可以将实例留在集合之外。
Obs.: I used this analogy to simplify my problem, but my real situation is: I have a model a user can generate instances of it. He can also create collections of those instances, but he can leave an instance outside a collection.
推荐答案
我认为这是绝对正常的方法。
I think it is absolutely normal approach.
您只需在 null
值中保留 house_id
不属于其他模型的数据库。
You can just leave house_id
with null
value in database for the models which don't belong to other.
这篇关于有关空的belongs_to关联的最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!