我有两个模型,产品和类别,以及一个连接表,分类,用于多对多关系。
假设我有两个对象,产品和类别,它们是上述的实例。
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
有任何想法吗?谢谢!