4

I have those two Models, in a HABTM Relationship:

The Project is using Rails 4, so no attr_accessible tags

wine.rb

class Wine < ActiveRecord::Base

  has_and_belongs_to_many :pairings, class_name: 'Food', join_table: 'foods_wines', association_foreign_key: 'food_id'
  has_many :images, as: :attachable, class_name: 'Asset', dependent: :delete_all
end

food.rb

class Food < ActiveRecord::Base
  has_and_belongs_to_many :wines, class_name: "Wine", join_table: "foods_wines", foreign_key: "food_id"
end

I created the Join Table with this migration:

create_table(:foods_wines, :id => false) do |t|
  t.integer :food_id
  t.integer :wine_id
end

add_index :foods_wines, [:food_id, :wine_id]

When I try to create the new Relation in the Rails Console, it does not seem to be saving the HABTM Relationship.

@wine.pairings.create(:name => "Seafood")

it does not seem to be saving the HABTM Relation -> When I restart the console, the relation is gone - I also checked inside the DB, where I get an empty table for the foods_wines table.

Am I missing something crucial here?

Martin Lang
  • 831
  • 11
  • 20

1 Answers1

0

I think, you have to replace :

has_and_belongs_to_many :pairings, class_name: 'Food', join_table: 'foods_wines', association_foreign_key: 'food_id'

with :

has_and_belongs_to_many :pairings, class_name: 'Food', join_table: 'foods_wines', foreign_key: 'wine_id'

in wine.rb, because you have to specify the foreign key of this class (Wine).

guitarman
  • 3,290
  • 1
  • 17
  • 27