爲了滿足業務需求,我不得不違反Rails約定,這給我帶來了一些痛苦。我的意圖是能夠通過兩種單獨的方法引用外部表(通過Rails)。Rails協會:通過非標準名稱訪問外部價值
在典型情況下,你有這樣的事情:
class Employee < ActiveRecord::Base
belongs_to :company
end
class Company < ActiveRecord::Base
has_many :employees
end
然後,您可以參考一個公司,通過Employee對象做類似如下:
e = Employee.find(1)
puts e.company.name
這一工程對於大多數表格來說都很好,但是可以說我們有如下表格:
id - integer default_channel_id - integer and foreign key reference to channel table selected_channel_id - integer and foreign key reference to channel table
如圖所示,不可能簡單地允許約定來決定如何建立關聯,因爲多於一列引用相同的外鍵值。
我一直在閱讀Rails documentation on associations,但是我還沒有找到任何可以讓我以這種方式定義關聯的東西。我得到的最接近的是通過:foreign_key選項,但僅憑這一點無效,因爲它使用名稱通道創建了一個單一方法。以下是我的嘗試:
class Foo < ActiveRecord::Base
belongs_to :channel, :foreign_key => "default_channel_id"
belongs_to :channel, :foreign_key => "selected_channel_id"
end
我應該怎麼辦?
注意:爲了以防萬一,我正在使用Ruby 1.9.2和Rails 3.0.3。
這奏效了!非常感謝你! – senfo 2010-12-24 15:54:18