我有这两个模型,在 HABTM 关系中:
该项目使用的是 Rails 4,所以没有 attr_accessible 标签
酒
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
食物.rb
class Food < ActiveRecord::Base
has_and_belongs_to_many :wines, class_name: "Wine", join_table: "foods_wines", foreign_key: "food_id"
end
我使用此迁移创建了连接表:
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]
当我尝试在 Rails 控制台中创建新关系时,它似乎没有保存 HABTM 关系。
@wine.pairings.create(:name => "Seafood")
它似乎没有保存 HABTM 关系 -> 当我重新启动控制台时,关系消失了 - 我还在数据库内部进行了检查,在那里我得到了一个空表 食品_葡萄酒 table 。
我在这里遗漏了一些重要的东西吗?
最佳答案
我认为,你必须更换:
has_and_belongs_to_many :pairings, class_name: 'Food', join_table: 'foods_wines', association_foreign_key: 'food_id'
和 :
has_and_belongs_to_many :pairings, class_name: 'Food', join_table: 'foods_wines', foreign_key: 'wine_id'
在
wine.rb
,因为您必须指定 foreign key
本类(葡萄酒)。
关于ruby-on-rails - 创建记录时不保存 HABTM 关联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17479240/