ruby on rails - Fill a table with a foreign key by default values -


i hope me that. have 2 table, want them related :

create_table "personals", force: :cascade |t| t.string   "trigramme" t.string   "nom" t.string   "prenom" t.string   "poste" t.text     "bio" t.integer  "user_id" t.datetime "created_at", null: false t.datetime "updated_at", null: false end 

and

create_table "users", force: :cascade |t| t.string   "email",                  default: "", null: false t.string   "encrypted_password",     default: "", null: false t.string   "reset_password_token" t.datetime "reset_password_sent_at" t.datetime "remember_created_at" t.integer  "sign_in_count",          default: 0,  null: false t.datetime "current_sign_in_at" t.datetime "last_sign_in_at" t.string   "current_sign_in_ip" t.string   "last_sign_in_ip" t.datetime "created_at",                          null: false t.datetime "updated_at",                          null: false end 

i have executed :

rails generate model personal trigramme:string nom:string ... user:references in order create foreign key , put belong_to (in personal) , has_one (in user) in model files.

do know how generate default value in table personal when user create account ? mean create new row in personal table, liked row created in user when account created?

my table user correctly fill when user create account.

best practice create has_one relation use activerecord callback before_create. activerecord automagically fills in foreign key in child record after saves parent record (on create). activerecord saves child record part of creating parent record.

class user < activerecord::base   has_one :personal   before_create :generate_profile    protected    def generate_profile     self.build_personal   end  end 

Comments

Popular posts from this blog

javascript - gulp-nodemon - nodejs restart after file change - Error: listen EADDRINUSE events.js:85 -

Fatal Python error: Py_Initialize: unable to load the file system codec. ImportError: No module named 'encodings' -

javascript - oscilloscope of speaker input stops rendering after a few seconds -