简体   繁体   English

Rails 3,has_one belongs_to问题

[英]Rails 3, has_one belongs_to issues

I've got a model called User with: 我有一个名为User的模型:

has_one :etho

And a model called Etho with: 还有一个名为Etho的模型:

belongs_to :user

I've got a build on the create method in User: 我在User中构建了create方法:

@user.build_etho

And for some reason when I login, I am still able to create more than 1 etho! 出于某种原因,当我登录时,我仍然可以创建超过1个etho! A user should only have 1 etho and shouldn't be able to create any more than 1! 用户应该只有1个etho,并且不能创建超过1个! Why isn't this working? 为什么这不起作用?

I think you misunderstand what build_etho does - according to the documentation 根据文档,我认为你误解了build_etho的作用

http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html

"build_association(attributes = {}) Returns a new object of the associated type that has been instantiated with attributes and linked to this object through a foreign key, but has not yet been saved." “build_association(attributes = {})返回已使用属性实例化并通过外键链接到此对象但尚未保存的关联类型的新对象。”

that is, each time you call build_etho, a new Etho object is created (build, that is, not saved in the db yet) - a user will always be linked to exactly one, probably the last created, but calling build_etho will not guarantee that only one is created from your User object! 也就是说,每次调用build_etho时,都会创建一个新的Etho对象(构建,即尚未保存在数据库中) - 用户将始终只链接到一个,可能是最后创建的,但调用build_etho不能保证只有一个是从您的User对象创建的!

What exactly are you trying to do? 你究竟想做什么?

Your reference id column should be in your users table, can you confirm please? 您的参考id列应该在您的users表中,您可以确认吗?

Which means that in your users migration you should have 这意味着您的用户迁移应该具备

t.references :ethos

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM