0

I'm running Rails 2.3.2 and doing:

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

and get the error

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 )

How can I get this working?

The Rails documentation on HBTM says:

WARNING: If you‘re overwriting the table name of either class, the table_name method MUST be declared underneath any has_and_belongs_to_many declaration in order to work.

What does this mean?

ma11hew28
  • 121,420
  • 116
  • 450
  • 651

1 Answers1

7

You'll need to use :foreign_key also in the has_and_belongs_to_many call. So in the StandardWidget model you need this:

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

The warning in the docs means that if you are using table names other than 'parts' for the Part model and 'standard_widgets' for the StandardWidget model, then you need to call 'set_table_name' beneath the habtm call.

Mike Gorski
  • 1,228
  • 1
  • 8
  • 13