Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/22.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 关于ActiveRecord关联和外键的混淆_Ruby On Rails_Ruby_Activerecord - Fatal编程技术网

Ruby on rails 关于ActiveRecord关联和外键的混淆

Ruby on rails 关于ActiveRecord关联和外键的混淆,ruby-on-rails,ruby,activerecord,Ruby On Rails,Ruby,Activerecord,在下面的示例中,我必须在Office模型中创建员工id,还是由db:migrate自动创建 感觉我错过了一些基本的东西。我正在尝试建立一个基本的一对多关系,在这里我可以使用下拉菜单从一侧选择对象。有没有什么好的基础图坦卡门来解释这是怎么回事 我必须在所有我想让它工作的模型中创建ID,但从我所看到的示例来看,它似乎不正确。ActiveRecord中的关联包括两部分。像您所做的那样将模型对象连接在一起并设置数据库。因此,您需要在迁移中定义关联,如下所示: def change create_ta

在下面的示例中,我必须在Office模型中创建员工id,还是由db:migrate自动创建

感觉我错过了一些基本的东西。我正在尝试建立一个基本的一对多关系,在这里我可以使用下拉菜单从一侧选择对象。有没有什么好的基础图坦卡门来解释这是怎么回事


我必须在所有我想让它工作的模型中创建ID,但从我所看到的示例来看,它似乎不正确。

ActiveRecord中的关联包括两部分。像您所做的那样将模型对象连接在一起并设置数据库。因此,您需要在迁移中定义关联,如下所示:

def change
  create_table :offices do |t|
    # Other migrations

    t.references :employee
  end
end

或者,您也可以执行t.integer:employee\u id,这也将达到相同的目的。

ActiveRecord中的关联包括两部分。像您所做的那样将模型对象连接在一起并设置数据库。因此,您需要在迁移中定义关联,如下所示:

def change
  create_table :offices do |t|
    # Other migrations

    t.references :employee
  end
end
或者,您也可以执行t.integer:employee\u id,这也将达到相同的目的。

两个步骤

首先,您必须在迁移文件的office表中创建一个employee_id字段。你会有这样的东西:

class CreateOffices < ActiveRecord::Migration
  def change
    create_table :offices do |t|
      t.string :name
      t.integer :employee_id

      t.timestamps
    end
  end
end
其次,必须在模型中定义关联。按照惯例,如果您命名外键字段employee\u id,则不必在模型中指定它的名称

class Office < ActiveRecord::Base
  belongs_to :employee
end
应该足够了。

两步

首先,您必须在迁移文件的office表中创建一个employee_id字段。你会有这样的东西:

class CreateOffices < ActiveRecord::Migration
  def change
    create_table :offices do |t|
      t.string :name
      t.integer :employee_id

      t.timestamps
    end
  end
end
其次,必须在模型中定义关联。按照惯例,如果您命名外键字段employee\u id,则不必在模型中指定它的名称

class Office < ActiveRecord::Base
  belongs_to :employee
end

应该足够了。

你读了吗?谢谢你的链接,我现在更明白了。你读了吗?谢谢你的链接,我现在更明白了。