Ruby on rails Rails中的关系数据库:我需要多少引用?
在我的rails应用程序中,一个人有多个:测量值,一个测量值属于一个人。 我将关联添加到模型文件中。然后我为这个关联编写了两个迁移Ruby on rails Rails中的关系数据库:我需要多少引用?,ruby-on-rails,ruby-on-rails-4,database-schema,foreign-key-relationship,Ruby On Rails,Ruby On Rails 4,Database Schema,Foreign Key Relationship,在我的rails应用程序中,一个人有多个:测量值,一个测量值属于一个人。 我将关联添加到模型文件中。然后我为这个关联编写了两个迁移 class AddMeasurementRefToPeople < ActiveRecord::Migration def change add_reference :people, :measurement, index: true, foreign_key: true end end 现在我怀疑我是否真的需要这两种迁移。现在,我在两种型号
class AddMeasurementRefToPeople < ActiveRecord::Migration
def change
add_reference :people, :measurement, index: true, foreign_key: true
end
end
现在我怀疑我是否真的需要这两种迁移。现在,我在两种型号中都有一个外键。一个还不够吗?
(如果是这样的话,我应该回滚两次迁移中的哪一次?根据您的协会,一个人有许多度量值,度量值只属于一个人 您只需要在测量表中输入person外键。无需向person添加
度量值\u id
,因为一个人有许多度量值
因此,AddPersonRefToMeasurements
就足够了
在模型中,你应该这样做
class Person < ActiveRecord::Base
has_many :measurements
end
class Measurement < ActiveRecord::Base
belongs_to :person
end
class-Person
一个就足够了。你不需要在人中添加度量值\u id
@Pavan你能在回答中更改你的评论吗?我恢复了我的迁移maud$rake db:migrate:down VERSION=20150730091740==20150730091740 addmeasurementtreftopole:reverting=====remove\n\u参考(:people,:measurement,{:index=>true,:foreign_key=>true})
my migrations list中没有提到此取消迁移,因此没有显示还原。但是,my DB schema.rb已更新并反映了还原的迁移。我是否应该在migrations文件夹中看到新的迁移文件?@Mauddev向下运行迁移旨在反转架构更改。它不会删除或者还原任何文件更改。AddMeasurementTreftOpole迁移应该被永久删除,并且不再运行。因此,在向下迁移之后(正如您在上一条注释中所做的那样,这将还原对架构的更改),您应该删除迁移文件。该文件应命名为db/migrate/20150730091740_add_measurement_ref_to_people.rb
。如果未删除此文件,则下次执行rake db:migrate
(将向上运行所有挂起的迁移)@wizadofogz谢谢!这是有道理的。与此同时,我发现了另一个解决方案:我添加了一个RemoveMeasurementRefromPeople migration。但是你的解决方案要简洁得多,我会记住的。
ActiveRecord::Schema.define(version: 20150730121109) do
create_table "measurements", force: :cascade do |t|
t.datetime "date"
t.integer "weight"
t.integer "bmi_calc"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "person_id"
end
add_index "measurements", ["person_id"], name: "index_measurements_on_person_id"
create_table "people", force: :cascade do |t|
t.string "name"
t.float "length"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "measurement_id"
end
add_index "people", ["measurement_id"], name: "index_people_on_measurement_id"
end
class Person < ActiveRecord::Base
has_many :measurements
end
class Measurement < ActiveRecord::Base
belongs_to :person
end