rails 中的关联是否自动生成?
Does association in rails generated automatically?
如果我有这样的命令和模型:
命令
$ bin/rails generate model User name:string firstname:string
$ bin/rails genarate model Profile username:string password:string
由 rails
生成的模型
class User < ApplicationRecord
has_one :profile
end
Class Profile < ApplicationRecord
belongs_to :user
end
迁移文件夹中的1:1关联是由rails自动生成的还是我必须自己实现?
ActiveRecord::Associations::ClassMethods 不会自动创建数据库列。这实际上是一个非常危险且不受欢迎的功能。您不希望 Rails 服务器在运行时更改数据库模式。这就是迁移的目的。
然而,您可以在生成器中使用 references
“类型”(也称为 belongs_to
),它创建一个外键列以及模型中的一个关联:
bin/rails g model Profile username:string password:string user:references
class CreateProfiles < ActiveRecord::Migration[7.0]
def change
create_table :profiles do |t|
t.string :username
t.string :password
t.references :user, null: false, foreign_key: true
t.timestamps
end
end
end
class Profile < ApplicationRecord
belongs_to :user
end
添加来自生成器的 has_one
或 has_many
关联没有等效项,因为它们实际上并不对应于 this 模型上的数据库列。
如果您需要在 table 中添加外键列,您可以通过生成迁移来完成:
bin/rails g migration AddUserIdToProfiles user:refereces
配置文件 (class CreateProfiles < ActiveRecord::Migration
) 的迁移文件应该有这样的外键声明:
t.references :user, null: false, foreign_key: true
完整代码:
create_table :profiles do |t|
t.string :username
t.string :password
t.references :user, null: false, foreign_key: true
t.timestamps
end
也可以使用生成器命令自动生成,方法是添加 user:references
,如下所示:
$ bin/rails genarate model Profile username:string password:string user:references
您还可以参考 Active Record Migrations 指南并在该页面上搜索“参考资料”。
如果我有这样的命令和模型:
命令
$ bin/rails generate model User name:string firstname:string
$ bin/rails genarate model Profile username:string password:string
由 rails
生成的模型class User < ApplicationRecord
has_one :profile
end
Class Profile < ApplicationRecord
belongs_to :user
end
迁移文件夹中的1:1关联是由rails自动生成的还是我必须自己实现?
ActiveRecord::Associations::ClassMethods 不会自动创建数据库列。这实际上是一个非常危险且不受欢迎的功能。您不希望 Rails 服务器在运行时更改数据库模式。这就是迁移的目的。
然而,您可以在生成器中使用 references
“类型”(也称为 belongs_to
),它创建一个外键列以及模型中的一个关联:
bin/rails g model Profile username:string password:string user:references
class CreateProfiles < ActiveRecord::Migration[7.0]
def change
create_table :profiles do |t|
t.string :username
t.string :password
t.references :user, null: false, foreign_key: true
t.timestamps
end
end
end
class Profile < ApplicationRecord
belongs_to :user
end
添加来自生成器的 has_one
或 has_many
关联没有等效项,因为它们实际上并不对应于 this 模型上的数据库列。
如果您需要在 table 中添加外键列,您可以通过生成迁移来完成:
bin/rails g migration AddUserIdToProfiles user:refereces
配置文件 (class CreateProfiles < ActiveRecord::Migration
) 的迁移文件应该有这样的外键声明:
t.references :user, null: false, foreign_key: true
完整代码:
create_table :profiles do |t|
t.string :username
t.string :password
t.references :user, null: false, foreign_key: true
t.timestamps
end
也可以使用生成器命令自动生成,方法是添加 user:references
,如下所示:
$ bin/rails genarate model Profile username:string password:string user:references
您还可以参考 Active Record Migrations 指南并在该页面上搜索“参考资料”。