2010-12-23 57 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