2014-01-30 29 views
0

我想在ActiveRecord中映射Sinatra my MySQL dB。 該數據庫不遵循ActiveRecord約定,所以我需要映射一切添加屬性到我的類。ActiveRecord many_to_many自定義表和列名

一對一以及一對一協會都可以,但是我有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 

但我不知道如何定義自定義連接表與自定義鍵。

回答

0

使用join_table選項。您還必須將table_name設置爲ArticleProduct,因爲它不遵循導軌約定

必須根據文檔中的此行設置habtm調用後的表名稱。

警告:如果你既覆蓋類的表名,表名 方法必須爲了工作任何 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