2013-05-21 70 views
0

我有has_many和两个模型之间的关联belongs_to如下:如何覆盖默认外键?

class Section < ActiveRecord::Base 
self.primary_key = 'id' 
has_many :rights 
end 

class Right < ActiveRecord::Base 
self.primary_key = 'id' 
belongs_to :section 
end 

节表具有ID和SECTION_ID列好。上面的代码通过部分表中的ID列将Right的部分关联到Section。我希望它通过SECTION_ID列进行关联。我怎么做?

回答

1

编辑:在第二次阅读我认为我误解了你的问题,你实际上想要关联到Section表中的主键以外的字段?这不是很常见,因此我的误解。

您需要使用:primary_key => 'field_name'代替:foreign_key

belongs_to :section, :primary_key => 'section_id' 
+0

是马特。我想涉及主键以外的字段。我的确如上面所说的通过指定外键来尝试,但那不起作用 – Rahul

+0

嗨@Rahul,我已经更新了我的答案。 – Matt

+0

工作。因此,即使我在正确的模型中定义了主键是'id',它是否在关联时覆盖它? – Rahul

0

尝试这样

class Section < ActiveRecord::Base 
self.primary_key = 'id' 
has_many :rights 
end 

class Right < ActiveRecord::Base 
self.primary_key = 'id' 
belongs_to :section, :foreign_key => "section_id" 
end 
+0

我试过这个,但它仍然通过相同的“ID”列关联 – Rahul

+0

这个答案和我一样,误解了你的问题。 OP正试图建立一个在Section表中使用非主键字段的关系。 – Matt

+0

Rahul,我们通常将两个表格与section_id进行关联。 – visnu