我是Rails的新手,无法使我的模型关系正常工作,我不知道原因。我已经尝试了很多方法并遵循了许多不同的教程,但无法找出正确的方法。你知道我的代码出了什么问题吗?如何测试?
我有两个模型,has_one关联用户和配置文件。配置文件属于用户。因此,每次添加用户时,我也会添加一个配置文件。
这是用户模型的迁移文件
class CreateUsers < ActiveRecord::Migration[5.1]
def change
create_table :users do |t|
t.string :email
t.string :password_digest
t.timestamps
end
end
end
这是配置文件模型的迁移文件
class CreateProfiles < ActiveRecord::Migration[5.1]
def change
drop_table :profiles
create_table :profiles do |t|
t.string :name
t.string :lastname
t.string :phone
t.string :address
t.string :city
t.string :state
t.string :country
t.string :gender, :limit => 10
t.string :zipcode
t.references :users, foreign_key: true
t.timestamps
end
end
end
型号简介
class Profile < ApplicationRecord
belongs_to :user
end
模型用户
class User < ApplicationRecord
has_secure_password
has_one :profile
end
谢谢!
我认为问题可能出在迁移上。
Profile
属于 User
,因此在create_profiles
迁移中,您应该具有:
t.references :user, foreign_key: true
(user
而不是users
(。
使用您的代码,Profile
模型将具有users_id
字段,而它应该具有user_id
。