在rails中使用带有has_one关联的构建

esp*_*net 136 ruby-on-rails database-relations associations has-one

在这个例子中,我创建了一个user没有profile,然后在profile为该用户创建一个.我尝试使用带有has_one关联的构建,但是爆炸了.我看到这个工作的唯一方法是使用has_many.本user应该只有最多只能有一个profile.

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

class User < ActiveRecord::Base
  has_one :profile
end

class Profile < ActiveRecord::Base
  belongs_to :user
end
Run Code Online (Sandbox Code Playgroud)

但当我这样做时:

user.build_profile 
Run Code Online (Sandbox Code Playgroud)

我收到错误:

ActiveRecord::StatementInvalid: Mysql::Error: Unknown column 'profiles.user_id' in 'where clause': SELECT * FROM `profiles` WHERE (`profiles`.user_id = 4)  LIMIT 1
Run Code Online (Sandbox Code Playgroud)

在rails中有一种方法可以有0或1个关联吗?

Har*_*tty 351

build方法的签名是不同 has_onehas_many关联.

class User < ActiveRecord::Base
  has_one :profile
  has_many :messages
end
Run Code Online (Sandbox Code Playgroud)

has_many关联的构建语法:

user.messages.build
Run Code Online (Sandbox Code Playgroud)

has_one关联的构建语法:

user.build_profile  # this will work

user.profile.build  # this will throw error
Run Code Online (Sandbox Code Playgroud)

阅读has_one关联文档以获取更多详细信息.

  • has_one的不同语法总是让我抓狂......该死的! (28认同)
  • 很有趣的是,这里最受好评和接受的答案是如何回答OP提出的问题. (11认同)
  • @Ajedi32 答案与问题标题匹配,但与正文不匹配。鉴于这个 (`build_&lt;association&gt;`) 在 Rails 中是一个非常奇怪和意想不到的行为,如果你明白我的意思的话,寻找这个答案的人比实际问题的答案要多得多。 (2认同)

sos*_*orn 18

仔细查看错误消息.它告诉您user_id配置文件表中没有必需的列.在模型中设置关系只是答案的一部分.

您还需要创建一个将user_id列添加到配置文件表的迁移.Rails希望它存在,如果不存在,则无法访问配置文件.

有关更多信息,请查看此链接:

协会基础知识