3

我有两个模型,产品和类别,以及一个连接表,分类,用于多对多关系。

假设我有两个对象,产品和类别,它们是上述的实例。

products = Product.new(...)
category = Category.new(...)
product.categories << category

这成功地在 rails 控制台中创建了两个方向的关系,因此:

product.categories
category.products

都是非空的。下一个:

product.categories.delete category

将从产品对象和连接表中删除值。但是它不会从类别对象中删除它,因此:

category.products

是非空的,这意味着内存中的 category.products 对象与实际数据库不同步。对我来说,创建会对称地工作但删除不会,这似乎很奇怪。

以下是相关型号:

class Product < ActiveRecord::Base
  has_many :categorizations, dependent: :destroy
  has_many :categories, through: :categorizations, :uniq => true
end

class Category < ActiveRecord::Base
  has_many :categorizations, dependent: :destroy
  has_many :products, through: :categorizations, :uniq => true
end

class Categorization < ActiveRecord::Base
  belongs_to :product, class_name: "Product"
  belongs_to :category, class_name: "Category"

  validates :product, presence: true
  validates :category, presence: true
end

有任何想法吗?谢谢!

4

2 回答 2

3

Answer: it's product.reload

This explanation is the first one I've found after hours searching: https://stackoverflow.com/a/7449957/456280

于 2012-09-07T12:42:09.390 回答
0

The behavior you're observing is the way Rails is designed to behave. See the Rails Guide on associations

You might also want to look at the section on has_and_belongs_to_many (HABTM) associations. HABTM would let you get rid of your explicit Categorization model if renamed the join table categories_products.

于 2012-09-06T21:11:35.187 回答