Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/ant/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby Rails关联:通过非标准名称访问外部值_Ruby_Associations_Ruby On Rails 3 - Fatal编程技术网

Ruby Rails关联:通过非标准名称访问外部值

Ruby Rails关联:通过非标准名称访问外部值,ruby,associations,ruby-on-rails-3,Ruby,Associations,Ruby On Rails 3,为了满足业务需要,我不得不打破Rails惯例,这给我带来了一些痛苦。我的目的是能够通过两种不同的方法(通过Rails)引用外部表 在一个典型的场景中,您会遇到如下情况: class Employee < ActiveRecord::Base belongs_to :company end class Company < ActiveRecord::Base has_many :employees end belongs_to :default_channel, :clas

为了满足业务需要,我不得不打破Rails惯例,这给我带来了一些痛苦。我的目的是能够通过两种不同的方法(通过Rails)引用外部表

在一个典型的场景中,您会遇到如下情况:

class Employee < ActiveRecord::Base
  belongs_to :company
end

class Company < ActiveRecord::Base
  has_many :employees
end

belongs_to :default_channel, :class_name => "Channel"
belongs_to :selected_channel, :class_name => "Channel"
这对大多数表都适用,但假设我们有如下表:

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 id-整数 默认信道id-信道表的整数和外键引用 选定的\u通道\u id-通道表的整数和外键引用 如图所示,不可能简单地允许约定确定如何建立关联,因为有多个列引用相同的外键值

我一直在阅读,但我还没有找到任何允许我以这种方式定义关联的东西。我得到的最接近的方法是:foreign_key选项,但仅此一项不起作用,因为它创建了一个名为channel的方法。以下是我的尝试:

class Foo < ActiveRecord::Base
  belongs_to :channel, :foreign_key => "default_channel_id"
  belongs_to :channel, :foreign_key => "selected_channel_id"
end
class Foo“默认频道\u id”
属于:频道,:外键=>“所选频道\u id”
结束
我该怎么做


注意:为了以防万一,我正在使用Ruby 1.9.2和Rails 3.0.3。

定义如下关联:

class Employee < ActiveRecord::Base
  belongs_to :company
end

class Company < ActiveRecord::Base
  has_many :employees
end

belongs_to :default_channel, :class_name => "Channel"
belongs_to :selected_channel, :class_name => "Channel"
这将引用数据库中的
default\u channel\u id
字段,以便在您请求时加载
default\u channel
关联,我打赌您可以利用这些信息了解调用
selected\u channel
类Fooclass Foo < ActiveRecord::Base
  belongs_to :default_channel, :class_name => "Channel"
  belongs_to :selected_channel, :class_name => "Channel"
end
属于:默认频道,:class\u name=>“频道” 属于:所选频道,:class\u name=>“频道” 结束

class频道'default\u channel\u id'
有多个:已选择的\u频道,:外部\u键=>“已选择的\u频道\u id”
结束