如何在rails中创建foreign_key和两个表?

问题描述:

我是新的轨道4。我有两个表喜欢这样的:如何在rails中创建foreign_key和两个表?

create_table "reservoirs", primary_key: "idEmbalse", force: :cascade, options: "ENGINE=InnoDB DEFAULT CHARSET=utf8" do |t| 
    t.string "nombre" 
    t.integer "idJunta" 
    t.datetime "created_at", null: false 
    t.datetime "updated_at", null: false 
    end 

    create_table "joints", primary_key: "idJunta", force: :cascade, options: "ENGINE=InnoDB DEFAULT CHARSET=utf8" do |t| 
    t.string "nombre" 
    t.string "color" 
    t.integer "numero" 
    t.datetime "created_at", null: false 
    t.datetime "updated_at", null: false 
    t.index ["nombre", "color", "numero"], name: "index_joints_on_nombre_and_color_and_numero", unique: true, using: :btree 
    end 

我试图创建关节和水库,但没有文件的工作之间的relathionship idJunta 。我怎么能关联idJunta? 。谢谢

最好在模型中分配主键而不是在迁移中,因为它可以更好地为自己和其他人读取。

create_table "reservoirs", force: :cascade, options: "ENGINE=InnoDB DEFAULT CHARSET=utf8" do |t| 
    t.string "nombre" 
    t.integer "idJunta" 
    t.datetime "created_at", null: false 
    t.datetime "updated_at", null: false 
    end 

    create_table "joints", force: :cascade, options: "ENGINE=InnoDB DEFAULT CHARSET=utf8" do |t| 
    t.string "nombre" 
    t.string "color" 
    t.integer "numero" 
    t.datetime "created_at", null: false 
    t.datetime "updated_at", null: false 
    t.index ["nombre", "color", "numero"], name: "index_joints_on_nombre_and_color_and_numero", unique: true, using: :btree 
    end 

运行耙分贝:迁移(或轨道DB:在轨道上5>迁移):

class Reservoir < MailForm::Base 
    self.primary_key = "person_id" 
end 

而在你的关节模型

在油藏模型

那么做到这一点:

class Joint < MailForm::Base 
    self.primary_key = "idJunta" 
end 
+0

我想创建ID之间的参考......这不行 –

+0

可以更改t.integer“idJunta”到t.references“idJunta “ – luissimo

你试过了吗使用has_many和belongs_to?

http://guides.rubyonrails.org/v4.2/association_basics.html

4.1.2.5:foreign_key

按照惯例,Rails的假设,用于保存这个模型外键的列后缀_id加入协会的名称。的:foreign_key选项,可以直接设置外键的名称:

class Order < ActiveRecord::Base 
    belongs_to :customer, class_name: "Patron", 
         foreign_key: "patron_id" 
end