2010-12-23 46 views
2

爲了滿足業務需求,我不得不違反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。

回答

3

定義的關聯是這樣的:

belongs_to :default_channel, :class_name => "Channel" 
belongs_to :selected_channel, :class_name => "Channel" 

這將引用default_channel_id領域在數據庫中,當你要求它加載default_channel協會和我與信息敢打賭,你可以計算出,當你調用會發生什麼selected_channel

+0

這奏效了!非常感謝你! – senfo 2010-12-24 15:54:18

1
class Foo < ActiveRecord::Base 
    belongs_to :default_channel, :class_name => "Channel" 
    belongs_to :selected_channel, :class_name => "Channel" 
end 

class Channel < ActiveRecord::Base 
    has_many :default_channels, :foreign_key => 'default_channel_id' 
    has_many :selected_channels, :foreign_key => 'selected_channel_id' 
end