2016-04-10 6 views
0

2つのテーブル(ユーザーとプロファイル)があります。テーブルのスキーマは次のとおりです。Ruby on rails:1対1のデータベース挿入での問題

create_table "users", force: :cascade do |t| 
    t.string "username" 
    t.string "password_digest" 
    t.datetime "created_at",  null: false 
    t.datetime "updated_at",  null: false 
end 

create_table "profiles", force: :cascade do |t| 
    t.string "gender" 
    t.integer "birth_year" 
    t.string "first_name" 
    t.string "last_name" 
    t.integer "user_id" 
    t.datetime "created_at", null: false 
    t.datetime "updated_at", null: false 
end 

モデルは次のとおりです。私は、次の手順でレコードを追加しようとしています

class Profile < ActiveRecord::Base 
    belongs_to :user 
end 

class User < ActiveRecord::Base 
    has_many :todo_lists 
    has_many :many_items, through: :todo_lists, source: :todo_items 
end 

user = User.create! username: "Fiorina",password_digest: "abc" 
user_profile = Profile.create! gender:"F",birth_year:"1954",first_name:"Carly",last_name:"Fiorina" 
user_profile.profile = user 

は、しかし、私は取得エラー:

"NoMethodError:未定義のメソッド 'profile =' for#"

エラーメッセージはクリアです。しかし、解決方法、つまりprofileメソッドの作成方法はわかりません。また、私は以下のブログを読んでおり、1対1の関係は4つの方法を作成すると言います。とにかく、4つのメソッドが作成されたことを確認する必要があります。

http://requiremind.com/differences-between-has-one-and-belongs-to-in-ruby-on-rails/

答えて

1

あなたはuser_profile

user_profile.user=user

userを設定する必要があります。しかし、同じことを行うには短い方法は、これは自動的にこのユーザーのプロファイルを作成します

user.create_profile(gender:"F",birth_year:"1954",first_name:"Carly",last_name:"Fiorina")

あります。

この時点で

class User < ActiveRecord::Base 
    has_one :profile 
    has_many :todo_lists 
    has_many :many_items, through: :todo_lists, source: :todo_items 
end 
を、それを保存したくない場合にも build_profileを使用することができます

1

あなたはそれを変更する必要があります。データベースのフィールドと関連名応じ

user_profile.user = user