Rails:在 Rails 中使用带有 has_one 关联的构建
在此示例中,我创建一个没有个人资料
的用户
,然后为该用户创建一个个人资料
。我尝试使用带有 has_one
关联的构建,但失败了。我看到这个工作的唯一方法是使用has_many
。 用户
应该最多只有一个个人资料
。
我一直在尝试这个。我有:
class User < ActiveRecord::Base
has_one :profile
end
class Profile < ActiveRecord::Base
belongs_to :user
end
但是当我这样做时:
user.build_profile
我收到错误:
ActiveRecord::StatementInvalid: Mysql::Error: Unknown column 'profiles.user_id' in 'where clause': SELECT * FROM `profiles` WHERE (`profiles`.user_id = 4) LIMIT 1
rails 中有没有办法进行 0 或 1 关联?
In this example, I create a user
with no profile
, then later on create a profile
for that user. I tried using build with a has_one
association but that blew up. The only way I see this working is using has_many
. The user
is supposed to only have at most one profile
.
I have been trying this. I have:
class User < ActiveRecord::Base
has_one :profile
end
class Profile < ActiveRecord::Base
belongs_to :user
end
But when I do:
user.build_profile
I get the error:
ActiveRecord::StatementInvalid: Mysql::Error: Unknown column 'profiles.user_id' in 'where clause': SELECT * FROM `profiles` WHERE (`profiles`.user_id = 4) LIMIT 1
Is there a way in rails to have 0 or 1 association?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
has_one
和has_many
关联的build
方法签名不同。has_many
关联的构建语法:has_one
关联的构建语法:阅读
has_one
关联 文档 了解更多详细信息。The
build
method signature is different forhas_one
andhas_many
associations.The build syntax for
has_many
association:The build syntax for
has_one
association:Read the
has_one
association documentation for more details.仔细查看错误消息。它告诉您个人资料表中没有必需的
user_id
列。在模型中设置关系只是答案的一部分。
您还需要创建一个迁移,将
user_id
列添加到配置文件表中。Rails 期望它存在,如果不存在,您将无法访问该配置文件。
有关更多信息,请查看此链接:
协会基础知识
Take a good look at the error message. It is telling you that you do not have required column
user_id
in the profile table.Setting the relationships in the model is only part of the answer.
You also need to create a migration that adds the
user_id
column to the profile table.Rails expects this to be there and if it is not you cannot access the profile.
For more information please take a look at this link:
Association Basics
它应该是一个
has_one
。如果build
不起作用,您可以使用new
:与
It should be a
has_one
. Ifbuild
isn't working, you can just usenew
:is the same as