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!
Answer: it's product.reload
This explanation is the first one I've found after hours searching: https://stackoverflow.com/a/7449957/456280
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With