【问题标题】:Rails has_and_belongs_to with primary key delete all records on destroy带有主键的 Rails has_and_belongs_to 在销毁时删除所有记录
【发布时间】:2018-01-29 14:16:19
【问题描述】:

我在 Rails 5 中有 3 个模型:

产品

 class Product < ApplicationRecord

    belongs_to :category
    has_and_belongs_to_many :stores

 end

商店

  class Store < ApplicationRecord
    has_many :admin_users
    has_and_belongs_to_many :roles
    has_and_belongs_to_many :products
  end

产品商店

  class ProductsStores < ApplicationRecord
    self.primary_key = :store_id
  end

当我尝试使用命令 ProductsStores.first.destroy 删除连接表 ProductsStores 的一条记录时,连接表中的所有记录都会被销毁。为什么?

谁能帮帮我?

提前谢谢你!

【问题讨论】:

    标签: mysql ruby-on-rails ruby


    【解决方案1】:

    首先,您必须通过以下方式了解 HABTM 和 has_many 之间的区别: http://guides.rubyonrails.org/association_basics.html#the-has-and-belongs-to-many-association 如果你创建了linkedin模型并想使用这个模型,你必须使用has_many through: association,并添加到这个模型belongs_to :productbelongs_to :store。然后使用标志dependent: :destroy,您可以默认销毁或不销毁链接模型。

    【讨论】:

      猜你喜欢
      • 2017-04-18
      • 2011-04-26
      • 2014-01-22
      • 2015-06-01
      • 2015-11-12
      • 2011-07-01
      • 2015-03-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多