使用建立在一个铁轨协会HAS_ONE [英] Using build with a has_one association in rails

查看:175
本文介绍了使用建立在一个铁轨协会HAS_ONE的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这个例子中,我创建了一个用户没有简介,再后来就创建一个简介为该用户。我试图用建立了 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆