无法与用户建立个人资料
Cant build profile with user
用户模型:
has_one :profile
before_create :build_profile # Works when using form views
个人资料模型
belongs_to :user
我在配置文件 table 上有 user_id
,所以所有设置都在那里。
我想用 console:
的配置文件创建一个用户
User.create!(....).build_profile(...)
我只得到用户,没有资料。
User.new(...).build_profile(...).save
#=> can't modify frozen Hash
怎么做?我确定我所做的是正确的。设计是否导致问题
我执行了相同的操作,但稍作改动,它按预期工作。
User.create!(name: 'Test user', email: "testuser@gmail.com", password: "password").build_profile.save
执行了以下查询。
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', 'a$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
模型代码以下,数据最少。
class User < ActiveRecord::Base
has_one :profile
end
个人资料模型
class Profile < ActiveRecord::Base
belongs_to :user
end
如果设计会给您带来问题,它必须在保存用户对象时在控制台中抛出验证错误。
编辑:配置文件迁移文件
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
用户模型:
has_one :profile
before_create :build_profile # Works when using form views
个人资料模型
belongs_to :user
我在配置文件 table 上有 user_id
,所以所有设置都在那里。
我想用 console:
的配置文件创建一个用户User.create!(....).build_profile(...)
我只得到用户,没有资料。
User.new(...).build_profile(...).save
#=> can't modify frozen Hash
怎么做?我确定我所做的是正确的。设计是否导致问题
我执行了相同的操作,但稍作改动,它按预期工作。
User.create!(name: 'Test user', email: "testuser@gmail.com", password: "password").build_profile.save
执行了以下查询。
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', 'a$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
模型代码以下,数据最少。
class User < ActiveRecord::Base
has_one :profile
end
个人资料模型
class Profile < ActiveRecord::Base
belongs_to :user
end
如果设计会给您带来问题,它必须在保存用户对象时在控制台中抛出验证错误。
编辑:配置文件迁移文件
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