【问题标题】:migration with two belongs_to for the same table同一个表的两个 belongs_to 迁移
【发布时间】:2013-12-11 17:15:50
【问题描述】:

我有接下来的两个模型

class Currency < ActiveRecord::Base
  # something ...
end

class CurrencyRate < ActiveRecord::Base
  attr_accessible :rate
  belongs_to :currency_to_convert, :class_name => 'Currency'
  belongs_to :currency_converted, :class_name => 'Currency'
end

我应该如何为 CurrencyRate 模型创建迁移,只有一个字段用于外键关联或两个字段?

我一直在考虑类似的事情

class CreateCurrencyRates < ActiveRecord::Migration
  def change
    create_table :currency_rates do |t|
      t.integer :currency_id
      t.timestamps
    end
  end
end

但我不确定是否适用于具有两个 belongs_to 关联的模型。

【问题讨论】:

  • 被转换成to_convert的别名了吗?
  • "currency_converted" 是我应该根据以“currency_converted”单位生成值应用汇率的货币
  • 他们都使用同一个foreign_key吗?
  • 不,不同的外键

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


【解决方案1】:
class CurrencyRate < ActiveRecord::Base
  attr_accessible :rate
  belongs_to :currency_to_convert, :class_name => 'Currency', :foreign_key => 'currency_convert_id'
  belongs_to :currency_converted, :class_name => 'Currency', :foreign_key => 'currency_converted_id'
end

class CreateCurrencyRates < ActiveRecord::Migration
  def change
    create_table :currency_rates do |t|
      t.integer :currency_converted_id
      t.integer :currency_convert_id
      t.timestamps
    end
  end
end

【讨论】:

    猜你喜欢
    • 2016-04-14
    • 2020-03-07
    • 1970-01-01
    • 2012-04-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-21
    • 1970-01-01
    相关资源
    最近更新 更多