Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete in Many to Many Relationship Not Symmetric?

I have two Models, Product and Category, and a join table, Categorizations, for the many-to-many relationship.

Let's say I have two objects, product and category, that are instances of the above.

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

This successfully creates the relationship in both directions in the rails console, so that:

product.categories
category.products

are both nonempty. Next:

product.categories.delete category

will delete the value from the product object and the join table. HOWEVER it will not delete it from the category object, so that:

category.products

is nonempty, which means that the in-memory category.products object is out of sync with the actual database. It seems weird to me that creation would work symmetrically but deletion would not.

Here are the relevant models:

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

Any ideas? Thanks!

like image 694
Rob Gonzalez Avatar asked Sep 05 '25 17:09

Rob Gonzalez


1 Answers

Answer: it's product.reload

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

like image 128
Rob Gonzalez Avatar answered Sep 07 '25 16:09

Rob Gonzalez