Rails HABTM table de jointure nom_table écraser
-
10-10-2019 - |
Question
Je Rails 2.3.2 en cours d'exécution et de faire:
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
et obtenir l'erreur
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 )
Comment puis-je obtenir ce travail?
Le documentation Rails sur HBTM dit:
ATTENTION: Si vous écrasez la nom de la table ou l'autre classe, la Procédé de table_name DOIT être déclarée sous toute has_and_belongs_to_many déclaration pour le travail.
Qu'est-ce que cela signifie?
La solution
Vous devez utiliser: foreign_key aussi dans l'appel has_and_belongs_to_many. Ainsi, dans le modèle StandardWidget vous avez besoin ceci:
has_and_belongs_to_many :parts, :join_table => "widgets_parts", :association_foreign_key => "widget_custom_id", :foreign_key => "part_custom_id"
L'avertissement dans les docs signifie que si vous utilisez des noms de table autres que des « parties » pour le modèle partiel et « standard_widgets » pour le modèle StandardWidget, alors vous devez appeler « set_table_name » sous l'appel HABTM.