我有一个表 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/