如何在rails5

时间:2017-02-22 21:39:43

标签: ruby-on-rails postgresql heroku foreign-keys

我正在使用Rails 5.0.1进行Web开发并在Heroku上部署我的应用程序。我使用postgreSQL作为Heroku的数据库,使用sqlite3作为我的本地开发数据库。

我需要将Accounts表的account_number列链接到Transactions表中的两列。 account_number列不是Accounts表的主键。

并且,“交易”表格中有一列from_account,我想将其链接到account_number表格中的Accounts列, 我想要链接到to_account表的account_number列的另一列 - Accounts

account_number不是帐户表的主键,但它是唯一的

我正在尝试在我的迁移文件中执行以下操作:

create_table :transactions do |t|
  t.string :from_account, foreign_key: true
  t.string :to_account, foreign_key: true
  t.timestamps
end

add_foreign_key :transactions, column: :from_account, :accounts, column: :account_number
add_foreign_key :transactions, column: :to_account, :accounts, column: :account_number

我的模型文件如下所示:

class Transaction < ApplicationRecord
  belongs_to :from_account, :foreign_key => 'from_account', :class_name => 'Account'
  belongs_to :to_account, :foreign_key => 'to_account', :class_name => 'Account'
end

但是这会给我的本地sqlite3数据库和Heroku的PostgreSQL数据库带来错误。

如何在Rails5中对这样的东西进行建模。 到目前为止,我在网上找到的所有教程都只讲述了如何链接到引用表的主键。

编辑:也许我的问题不清楚,但是account_number字段在我的数据库的Accounts表中已经是唯一的。这是我的Accounts表的架构:

create_table :accounts do |t|
  t.string :account_number, :unique => true
  # Other fields
  t.timestamps
end

3 个答案:

答案 0 :(得分:6)

尝试primary_key:

class Transaction < ApplicationRecord
  belongs_to :from_account, :foreign_key => 'from_account', :class_name  => 'Account', :primary_key => 'account_number'
  belongs_to :to_account, :foreign_key => 'to_account', :class_name => 'Account', :primary_key => 'account_number'
end

答案 1 :(得分:3)

正如Arcana's answer所述,通过:primary_key

提供引用的列
class Transaction < ApplicationRecord
  belongs_to :from_account, :foreign_key => 'from_account', :class_name => 'Account',
    :primary_key => 'account_number'
  belongs_to :to_account, :foreign_key => 'to_account', :class_name => 'Account',
    :primary_key => 'account_number'
end

:primary_key中的语言belongs_to具有误导性。它应该是:candidate_key:references:uniqueprimary_key_or_unique。但它不是。它不会影响引用类中的主键。

Active Record Associations

  

4详细的协会参考
  4.1 belongs_to协会参考
  4.1.2 belongs_to的选项
  4.1.2.6 :primary_key

     

按照惯例,Rails假定id列用于保存其表的主键。 :primary_key选项允许您指定其他列。

(在关系模型中,外键引用候选键,它是一些唯一(非空)列集,不包含较小的唯一(非空)列集,并且是一组列您可以选择作为主键。但是在(Active Record和)SQL中,PRIMARY KEY实际上声明了UNIQUE NOT NULL(可能包含较小的UNIQUE NOT NULL)和FOREIGN KEY { {1}} REFERENCES。)

答案 2 :(得分:0)

我猜这是因为没有指定主键during your migrationwithin your model

相关问题