如何在rails中创建带有两个表的foreign_key?

时间:2016-09-20 09:34:51

标签: ruby-on-rails ruby-on-rails-4

我是rails 4的新手。我有两张桌子喜欢这个:

  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

我尝试创建一个关系idJunta 在关节和水库之间,但没有任何文件工作。我怎么能和idJunta联系? 。谢谢

2 个答案:

答案 0 :(得分:1)

您是否尝试使用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

答案 1 :(得分:0)

最好在模型中而不是在迁移中分配主键,因为它对您自己和其他人来说更具可读性。

  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

运行rake db:migrate(或rails db:migrate on rails 5&gt;)

然后在您的水库模型中执行此操作:

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

在你的联合模型中:

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