ActiveRecord many_to_many具有自定义表和列名称

时间:2014-01-30 15:58:17

标签: mysql ruby-on-rails ruby activerecord

我正在尝试使用ActiveRecord我的MySQL dB在Sinatra中进行映射。 db不遵循ActiveRecord约定,因此我需要将添加属性的所有内容映射到我的类。

对于一对多和一对一的关联,一切都很好,但我对m到m有问题。

我有一个名为“Eve_Articles”的文章表

我有一个名为“Eve_product”的产品平板电脑

我有一个名为“Eve_Articles_Product”的连接表,其中tree_id是文章ID,prod_id是产品ID。

我创建模型:

class Article < ActiveRecord::Base
  self.inheritance_column = :_type_disabled
  has_one :image, class_name: 'Image', foreign_key: 'tree_id'
  has_and_belongs_to_many :products, 

end

class Product< ActiveRecord::Base
  self.inheritance_column = :_type_disabled
  has_and_belongs_to_many :articles, 
end

但我不知道如何使用自定义键定义自定义连接表。

1 个答案:

答案 0 :(得分:1)

使用join_table选项。此外,您必须为table_nameArticle设置Product,因为它不遵循铁路惯例

根据文档中的这一行,您必须在habtm调用之后设置表名。

  

警告:如果你要覆盖任一类的表名,那么   table_name方法必须在any下面声明   has_and_belongs_to_many声明以便工作。

class Article < ActiveRecord::Base 
  self.inheritance_column = :_type_disabled
  has_one :image, class_name: 'Image', foreign_key: 'tree_id'
  has_and_belongs_to_many :products, :join_table => "Eve_Articles_Product", :association_foreign_key => 'tree_id', :foreign_key => 'prod_id'
  self.table_name = "Eve_Products"
end

class Product< ActiveRecord::Base
  self.inheritance_column = :_type_disabled
  has_and_belongs_to_many :articles, :join_table => "Eve_Articles_Product", :association_foreign_key => "prod_id", :foreign_key => 'tree_id'
  self.table_name = "Eve_Articles"
end