使用建立在一个铁轨协会HAS_ONE [英] Using build with a has_one association in rails
问题描述
在这个例子中,我创建了一个用户
没有简介
,再后来就创建一个简介
为该用户。我试图用建立了 HAS_ONE
关联但炸毁了。我看到这个工作是使用的唯一方法的has_many
。在用户
应该只有最多只能有一个简介
。
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
我得到的错误:
ActiveRecord::StatementInvalid: Mysql::Error: Unknown column 'profiles.user_id' in 'where clause': SELECT * FROM `profiles` WHERE (`profiles`.user_id = 4) LIMIT 1
是否有轨办法有0或1的关联?
Is there a way in rails to have 0 or 1 association?
推荐答案
的建立
方法签名是不同的 HAS_ONE
和的has_many
的关联。
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
协会<一个href=\"http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#M001834\">documentation了解更多详情。
这篇关于使用建立在一个铁轨协会HAS_ONE的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!