Rails:在Rails中使用带有has_one关联的build [英] Rails: Using build with a has_one association in rails

查看:185
本文介绍了Rails:在Rails中使用带有has_one关联的build的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在此示例中,我创建一个没有profileuser,然后为该用户创建一个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_onehas_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屋!

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