belongs_to :resellercategory
has_one :subcategory, :through => :resellercategory
has_one :category, :through => :subcategory
So, there are a lot of resellercategories that are (manually) mapped to my fewer subcategories.
I have a before_save in my products model that sets if the product is complete:
def check_complete
self.complete = !image_small.blank? && !subcategory.blank?
nil
end
So, if the resellercategory that the product is related to is mapped to a subcategory, the product is marked as "complete". However, at the moment it is only updated when the product is saved, I also want it to be updated when the resellercategory is mapped to a subcategory.
Is there any good way to do this? Should I create an after_save in my resellercategory that iterates through all the products and re-saves all of them to get the field updated?
Any easier/more effective way?
Regards
Linus
def update_products
self.products.each(&:save)
end
I'll see if I can get the scope to work first.
Regards
Linus
Thank you Peter. I have some follow up questions.Let's say I would use a scope. How could I do that? (let's ignore the "image_small" for now and focus on the subcategory) There is nothing in the product table that I can use to select the completed products. It is only regarded as completed if the related resellercategory is associated to a subcategory. So, in the scope I would need to join the resellercategories table and check if that is associated with a subcategory.
Feels a bit unnecessary to do that for a small thing as this. But maybe it won't affect the performance that much.
The other option I was thinking of was just to add an after_filter in resellercategory model like this:def update_products
self.products.each(&:save)
end