【问题标题】:Not saving the HABTM Association when creating a record创建记录时不保存 HABTM 关联
【发布时间】:2013-07-04 23:30:04
【问题描述】:

我有这两个模型,在 HABTM 关系中:

项目使用的是 Rails 4,所以没有 attr_accessible 标签

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

我使用此迁移创建了联接表:

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 => "海鲜")

它似乎没有保存 HABTM 关系 -> 当我重新启动控制台时,关系消失了 - 我还检查了数据库内部,在那里我得到了 foods_wines 表的空表.

我在这里遗漏了什么重要的东西吗?

【问题讨论】:

  • 你的 attr_accessible 标签在哪里?
  • Rails 4,强大的参数将其带走。
  • 请尝试运行@wine.pairings.create!(:name =&gt; "Seafood")查看是否有异常。

标签: ruby-on-rails has-and-belongs-to-many


【解决方案1】:

我认为,你必须更换:

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中,因为你必须指定这个类(Wine)的foreign key

【讨论】:

    猜你喜欢
    • 2015-11-07
    • 2011-04-29
    • 1970-01-01
    • 2023-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多