Do not save HABTM association when creating a record

I have these two Models regarding the HABTM:

The project uses Rails 4, so there are 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 a 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 a new Relation in the Rails Console, it does not seem to retain the HABTM relationship.

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

it looks like this is not saving the HABTM relationship -> When I restart the console, the relation disappeared - I also checked inside the DB where I get an empty table for the food_wines table.

Did I miss something important here?

+4
source share
1 answer

I think you should 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 must specify the foreign key this class (Wine).

0
source

Source: https://habr.com/ru/post/1489811/


All Articles