[英]Has_one, Belongs_to migration
I'm having a little bit of trouble truly understanding how this concept would work. 我在真正理解这个概念如何工作时遇到了一些麻烦。 First I'm going to use the devise gem for user authentication and activation, but I need to know how my migrations should look. 首先,我将使用devise gem进行用户身份验证和激活,但是我需要知道迁移的外观。 I have a unique key (user will be given) that will be used to activate an account. 我有一个唯一的密钥(将给用户),该密钥将用于激活帐户。
So here's what my code looks like VERY early on, mind you: 因此,请注意,这是我的代码非常早的样子:
User Model 用户模型
class User < ActiveRecord::Base
has_one :safe
has_many :contacts
end
Safe Model 安全模型
class Safe < ActiveRecord::Base
belongs_to :user
end
CreateSafes Migration file CreateSafes迁移文件
class CreateSafes < ActiveRecord::Migration
def change
create_table :saves do |t|
t.string :safe_key
t.timestamps
end
end
end
CreateUsers Migration CreateUsers迁移
class CreateUsers < ActiveRecord::Migration
def change
create_table :users do |t|
t.string :email
t.string :password
t.timestamps
end
end
end
I'm really just not sure if I add a user_id value to the safe migration table, or whether I just use the safe_key, since that's going to be a totally unique value. 我真的只是不确定是否要向安全迁移表中添加user_id值,还是仅使用safe_key,因为这将是一个完全唯一的值。 Any help and wisdom would be appreciated. 任何帮助和智慧将不胜感激。 Thanks. 谢谢。
Yes, manually add user_id to the safe table. 是的,手动将user_id添加到安全表中。 In associations, rails stores foreign keys in the table with the :belongs_to
Then you could use safe.user
to get the user, or user.safe
to get the safe. 在关联中,rails使用:belongs_to
将外键存储在表中。然后,您可以使用safe.user
来获取用户,或者使用user.safe
来获取安全。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.