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

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

问题描述

在这个例子中,我创建了一个没有 profileuser,然后为那个用户创建了一个 profile.我尝试将 build 与 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.

我一直在尝试这个.我有:

I have been trying this. I have:

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?

推荐答案

build 方法签名对于 has_onehas_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 关联文档 了解更多详情.

Read the has_one association documentation for more details.

这篇关于Rails:在 rails 中使用带有 has_one 关联的构建的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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