Rails:在Rails中使用带有has_one关联的build [英] Rails: Using build with a has_one association in rails
问题描述
在此示例中,我创建一个没有profile
的user
,然后为该用户创建一个profile
.我尝试将构建与has_one
关联一起使用,但此操作失败了.我看到此工作的唯一方法是使用has_many
. user
应该最多只有一个profile
.
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
.
我一直在尝试.我有:
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具有关联?
Is there a way in rails to have 0 or 1 association?
推荐答案
对于has_one
和has_many
关联,build
方法签名是不同的.
The build
method signature is different for has_one
and has_many
associations.
class User < ActiveRecord::Base
has_one :profile
has_many :messages
end
has_many
关联的构建语法:
user.messages.build
has_one
关联的构建语法:
user.build_profile # this will work
user.profile.build # this will throw error
阅读has_one
关联文档了解更多详细信息
Read the has_one
association documentation for more details.
这篇关于Rails:在Rails中使用带有has_one关联的build的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!