6

私は2つのテーブルを持っています:

通貨とレート

currencies: id:int, code:string, name: string

rates: id:int, top_currency_id:int, bottom_currency_id:int, rate:float

そして、私はそれらのために2つのアクティブなレコードを持っています:

class Rate < ActiveRecord::Base
  attr_accessible :bottom_currency, :rate, :top_currency, :top_currency_id

  belongs_to :top_currency, :class_name => 'Currency', :foreign_key => 'top_currency_id'
  belongs_to :bottom_currency, :class_name => 'Currency', :foreign_key => 'bottom_currency_id'
end


class Currency < ActiveRecord::Base
  attr_accessible :code, :name

  has_many :rates
end

問題は次のとおりです。次のコードを実行しようとすると: top_currency = Currency.find_by_id(1) @test = Rate.where(:top_currency=>top_currency)

次のエラーが表示されます:

Mysql2::Error: Unknown column 'rates.top_currency' in 
'where clause': SELECT `rates`.* FROM `rates`  WHERE `rates`.`top_currency` = 1

Rails の魔法が効かないのはなぜですか?

どうもありがとう。

4

3 に答える 3

6

2 つのbelongs_to方法で、foreign_keyオプションをに変更し、primary_key他のすべてはそのままにします。

belongs_to :top_currency, :class_name => 'Currency', :primary_key => 'top_currency_id'
# ...

デフォルトでは、関連付けられたオブジェクトの主キーはidです。ただし、通貨モデルには 3 つの主キーと、期待されるidと 2 つの追加キーがあります:top_currency_idbottom_currency_id. Active Record は、探すキーを知る必要があります。オプションで伝えprimary_keyます。

このオプションは、外部キーが関連付けの名前 ( ) に " " を加えforeign_keyたものと異なる場合に必要です。外部キーはアソシエーション名に " ," を加えたものと一致するため、オプション を使用する必要はありません。belongs_to :name_id_idforeign_key

于 2013-02-24T20:53:13.143 に答える
5

私が見たところ、あなたのコードは理論的には機能するはずです。しかし、あなたは少し冗長だと思います。

これを行うだけで十分なはずです:

class Rate < ActiveRecord::Base
  belongs_to :top_currency, class_name: 'Currency'
  belongs_to :bottom_currency, class_name: 'Currency'
end

top_currencyRails は、 の外部キーが でありtop_currency_id、 であると推測しbottom_currency_idますbottom_currency

于 2013-02-24T20:45:09.450 に答える
0

そのような関係を照会することはできないと思います。あなたの例を使用するには:

top_currency = Currency.find_by_id(1)
@test = Rate.where(:top_currency=>top_currency)

これを次のように変更する必要があります。

top_currency = Currency.find_by_id(1)
@test = Rate.where(:top_currency_id => top_currency.id)

しかし、これを行う方が簡単かもしれません:

top_currency = Currency.find_by_id(1)
@test = top_currency.rates
于 2013-02-25T02:02:22.730 に答える