Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/58.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails rails在两个现有模型之间创建关系_Ruby On Rails - Fatal编程技术网

Ruby on rails rails在两个现有模型之间创建关系

Ruby on rails rails在两个现有模型之间创建关系,ruby-on-rails,Ruby On Rails,我有两种型号: Account Profile 创建这些模型在数据库中创建了两个表: accounts profiles 现在我想添加一个关系: 每个帐户可以有许多配置文件 每个配置文件属于一个帐户 我运行了以下命令: rails g migration AddAccountToProfiles account:references 它创建了以下迁移: class AddAccountToProfiles < ActiveRecord::Migration def chang

我有两种型号:

Account
Profile
创建这些模型在数据库中创建了两个表:

accounts
profiles
现在我想添加一个关系:

  • 每个帐户可以有许多配置文件
  • 每个配置文件属于一个帐户
我运行了以下命令:

rails g migration AddAccountToProfiles account:references
它创建了以下迁移:

class AddAccountToProfiles < ActiveRecord::Migration
  def change
    add_reference :profiles, :account, index: true, foreign_key: true
  end
end
class AddAccountToProfiles
现在我有点困惑:

为什么迁移会说
:profiles
:account
?它不应该是
:accounts
(复数)吗

另外,在创建此迁移之后(或之前),我必须在相应的模型类中添加
属于
有许多
,对吗

作为一个附带问题,是否有一种方法可以将
属于
并且
在模型中有许多
,并且从这些信息中,rails生成适当的迁移,而无需我使用
'rails g migration…'
命令手动创建迁移?

根据

rails g migration AddAccountToProfiles account:references
将生成下面的迁移文件

class AddAccountToProfiles < ActiveRecord::Migration
  def change
    add_reference :profiles, :account, index: true, foreign_key: true
  end
end
class AddAccountToProfiles
由于您指定了
account:references
,因此它假定在
profiles
表上创建
account\u id
,但您仍然需要在相应的模型文件中添加关系

当我们在迁移文件中使用
:accounts
时,它引用数据库中的表,
:account
用作要添加到表中的外键的名称以及后缀
\u id


还有相关信息

迁移是正确的,因为配置文件只属于一个帐户。它不应该是“账户”。迁移将在profiles表中放置一个
account\u id
列,以便建立连接

迁移之后,您仍然需要添加
has\u many
belling\u to
。在Rails中,定义关系时,通常有两个步骤:1)创建数据库迁移2)在模型类本身上定义关系。你需要两者兼得。在本例中,Rails在配置文件(默认外键)上查找
account\u id
列,以建立两个模型之间的关系


至于你的最后一个问题,不,在定义了一个
has\u many
之后,没有办法生成迁移。您可以使用Rails生成器创建模型本身
Rails generate ModelName
,并在该模型中定义关系;这将在迁移过程中向生成的模型中添加正确的
所属的
,并且
有许多
。但在实践中,通常最好创建迁移并手动添加
所属的
,并且
根据需要有许多
,这样就不太可能遗漏某些内容。

@luskeer我实际阅读了答案,这就是我学会使用迁移命令的地方,但是我想了解为什么生成单数/复数名称的详细信息。根据,该命令将生成上面的迁移文件,因为您指定了user:references,然后它假设在
profiles
表上创建
user\u id
,但您仍然需要在相应的模型文件中添加关系。当我们在迁移文件中使用
:accounts
时,它指的是表,
:account
用作要添加到表中的外键的名称以及后缀
\u id
@luskeer。您应该添加它作为答案