sql - rails 3 : Can't create relationship :has_one

标签 sql mysql ruby-on-rails ruby-on-rails-3

我有一个表 User 和一个表 Profile。

这是我在用户中的内容:

# Table name: users
#
#  id                   :integer         not null, primary key
#  email                :string(255)     default(""), not null
#  encrypted_password   :string(128)     default(""), not null
#  password_salt        :string(255)     default(""), not null
#  reset_password_token :string(255)
#  remember_token       :string(255)
#  remember_created_at  :datetime
#  sign_in_count        :integer         default(0)
#  current_sign_in_at   :datetime
#  last_sign_in_at      :datetime
#  current_sign_in_ip   :string(255)
#  last_sign_in_ip      :string(255)
#  created_at           :datetime
#  updated_at           :datetime
#  admin                :boolean
#

  has_one :profile

个人简介:

# Table name: profiles
#
#  id           :integer         not null, primary key
#  user_id      :integer
#  organization :string(255)
#  phone        :string(255)
#  mobile       :string(255)
#  fax          :string(255)
#  address      :string(255)
#  city         :string(255)
#  zipcode      :string(255)
#  province     :string(255)
#  country      :string(255)
#  description  :text
#  url          :string(255)
#  skype        :string(255)
#  im           :string(255)
#  name         :string(255)
#  permalink    :string(255)
#  created_at   :datetime
#  updated_at   :datetime
#

  belongs_to :user

但是当我尝试运行 User.find(3).profile.build(:user_id => 3)User.find(3).profile.create(:user_id => 3)我收到该方法不存在的错误。

我在这里做错了什么?

编辑:ruby-1.9.2-rc2 > Profile.create(:user_id => 10) 运行良好。

最佳答案

我想你想要的是:

@user = User.find(3)
@profile = @user.build_profile()

这将创建并关联新配置文件,但不会保存它。

也用它来保存它:

@user = User.find(3)
@profile = @user.create_profile()

参见此处:http://guides.rubyonrails.org/association_basics.html#belongs_to-association-reference

关于sql - rails 3 : Can't create relationship :has_one,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4505181/

相关文章:

mysql - 如何编写单个查询来显示我的第一条记录被放置在最后一个位置

java - ORA-00907缺少右括号错误+java

sql - 基于另一列的 PostgreSQL 序列

php - 如何将存储的密码从 SHA1 更新为 password_hash

mysql - 使用 :has_many associations and multiple conditions 查找

ruby-on-rails - 使用 RSpec,如何在加载时为数据库设定种子?

sql - 如何在 pl sql 脚本中打印 select 语句?

返回SQL结果的php函数

mysql - 使用 Table.Column 是否可以提高性能?

ruby-on-rails - 在 Rails Capistrano 中跳过 backup_manifest 任务