Ruby-on-rails 关于空的belongs_to 关联的最佳实践
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10462676/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Best practice about empty belongs_to association
提问by Jo?o Daniel
Imagine the following situation:
想象一下以下情况:
I have a dogmodel and a housemodel. A dog can belong to a house, and a house can have many dogs, so:
我有一个dog模型和一个house模型。一只狗可以属于一个房子,一个房子可以有很多狗,所以:
Class Dog < ActiveRecord::Base
belongs_to :house
end
Class House < ActiveRecord::Base
has_many :dogs
end
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_idwhen creating it?
现在,想象一下我也想创造没有房子的狗。他们不属于房子。我是否仍然可以使用该关系结构并且:house_id在创建它时不通知 a ?
Is there a better practice?
有没有更好的做法?
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.
观察:我用这个比喻来简化我的问题,但我的真实情况是:我有一个模型,用户可以生成它的实例。他还可以创建这些实例的集合,但他可以将实例留在集合之外。
采纳答案by Flexoid
I think it is absolutely normal approach.
我认为这是绝对正常的方法。
You can just leave house_idwith nullvalue in database for the models which don't belong to other.
你可以只留下house_id与null价值在数据库中不属于其他车型。
回答by Wibbly
Be careful with this in Rails 5 ...
在 Rails 5 中小心这一点......
belongs_to is required by default
From now on every Rails application will have a new configuration option config.active_record.belongs_to_required_by_default = true, it will trigger a validation error when trying to save a model where belongs_to associations are not present.
config.active_record.belongs_to_required_by_default can be changed to false and with this keep old Rails behavior or we can disable this validation on each belongs_to definition, just passing an additional option optional: true as follows:
class Book < ActiveRecord::Base belongs_to :author, optional: true end
默认情况下需要belongs_to
从现在开始,每个 Rails 应用程序都会有一个新的配置选项 config.active_record.belongs_to_required_by_default = true,它会在尝试保存不存在关联的模型时触发验证错误。
config.active_record.belongs_to_required_by_default 可以更改为 false 并保持旧的 Rails 行为,或者我们可以在每个belongs_to 定义上禁用此验证,只需传递一个附加选项 optional: true 如下:
class Book < ActiveRecord::Base belongs_to :author, optional: true end

