0

我運行的Rails 2.3.2和做:Rails的HBTM join_table overwirting table_name的

class StandardWidget < ActiveRecord::Base 
    has_and_belongs_to_many :parts, :join_table => "widgets_parts", :association_foreign_key => "widget_custom_id" 
end 

class Part < ActiveRecord::Base 
    has_and_belongs_to_many :widgets, :join_table => "widgets_parts", :association_foreign_key => "part_custom_id" 
end 

p = StandardWidget.find(5) 
p.widgets 

並且得到錯誤

ActiveRecord::StatementInvalid: Mysql::Error: Unknown column 'widgets_parts.standard_widget_id' in 'where clause': SELECT * FROM `widgets` INNER JOIN `widgets_parts` ON `parts`.part_custom_id = `widgets_parts`.part_custom_id WHERE (`widgets_parts`.standard_widget_id = 5) 

我怎樣才能得到這個工作?

Rails documentation on HBTM說:

警告:如果你既覆蓋類的 表名,表名 方法必須爲了工作宣告 任何has_and_belongs_to_many 聲明下方。

這是什麼意思?

回答

5

您還需要在has_and_belongs_to_many調用中使用:foreign_key。因此,在StandardWidget模型,你需要這樣的:

has_and_belongs_to_many :parts, :join_table => "widgets_parts", :association_foreign_key => "widget_custom_id", :foreign_key => "part_custom_id" 

在文檔中的警告意味着,如果您使用的不是爲零件模型「部分」和「standard_widgets」爲StandardWidget模型的其他表名,那麼你需要在habtm調用下調用「set_table_name」。

+0

工作!謝謝! – ma11hew28 2010-12-09 16:44:15

相關問題