I have a table User and a table Profile.
Here's what I have in User:
# 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
In 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
But when I try to run User.find(3).profile.build(:user_id => 3)
or User.find(3).profile.create(:user_id => 3)
I get the error that the method does not exist.
What am I doing wrong here?
Edit: ruby-1.9.2-rc2 > Profile.create(:user_id => 10)
works well.
I think what you want is:
@user = User.find(3)
@profile = @user.build_profile()
This will create and associate the new profile but not save it.
Use this to save it also:
@user = User.find(3)
@profile = @user.create_profile()
See here: http://guides.rubyonrails.org/association_basics.html#belongs_to-association-reference
精彩评论