【发布时间】:2012-09-07 20:42:09
【问题描述】:
我有两个模型,产品和类别,以及一个连接表,分类,用于多对多关系。
假设我有两个对象,产品和类别,它们是上述的实例。
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
有什么想法吗?谢谢!
【问题讨论】:
-
至于下面,我发现如果我通过 product = Product.find(product.id) 重新加载产品,那么 product.categories确实是[]。我不想每次引用一个对象时都要使用 X.find 来确保对象中的数据是有效的;是否有另一种方法可以确保对象通过删除保持最新?发布/订阅方法还是什么?
标签: ruby-on-rails ruby-on-rails-3