Sylar Sylar - 5 days ago 4
Ruby Question

Cant build profile with user

User Model:

has_one :profile
before_create :build_profile # Works when using form views


Profile Model

belongs_to :user


I have the
user_id
on the profiles table so all is set there.

I want to create a user with profile from console:

User.create!(....).build_profile(...)


I only get the user but no profile.

User.new(...).build_profile(...).save
#=> can't modify frozen Hash


How to go about doing this? I'm sure what I did was correct. Is devise causing an issue

Answer

I performed the same operation with minor changes and it works as expected.

User.create!(name: 'Test user', email: "testuser@gmail.com", password: "password").build_profile.save

Below queries were executed.

BEGIN
  User Exists (35.8ms)  SELECT  1 AS one FROM `users` WHERE   (`users`.`email` = BINARY 'testuser@gmail.com' AND `users`.`deleted_at` IS NULL) LIMIT 1
 SQL (7.0ms)  INSERT INTO `users` (`name`, `email`, `encrypted_password`, `created_at`, `updated_at`) VALUES ('Test user', 'testuser@gmail.com', '$2a$10$adX3zznn6R5G94WY5CtCZOHAVYZCXBD/ASDdyoDU7jl8P9RmRJUmC', '2016-12-01 13:41:07', '2016-12-01 13:41:07')
  (2.6ms)  COMMIT
  Profile Load (0.4ms)  SELECT  `profiles`.* FROM `profiles` WHERE `profiles`.`user_id` = '43' LIMIT 1
 (0.1ms)  BEGIN
 SQL (0.3ms)  INSERT INTO `profiles` (`user_id`, `created_at`, `updated_at`) VALUES ('43', '2016-12-01 13:41:07', '2016-12-01 13:41:07')
 (1.7ms)  COMMIT  => true 

Below model code with minimal data.

    class User < ActiveRecord::Base
      has_one :profile
    end

Profile model

    class Profile < ActiveRecord::Base
      belongs_to :user  
    end

If devise would create an issue for you, it must throw an validation error in console while saving the user object.

Edit: profile migration file

   class CreateProfiles < ActiveRecord::Migration
     def change
       create_table :profiles do |t|
        t.string :user_id
        t.string :Description

        t.timestamps null: false
       end
    end
  end