Getting ActiveRecord::RecordInvalid error with has_many through association; validation issue on join table Getting ActiveRecord::RecordInvalid error with has_many through association; validation issue on join table ruby ruby

Getting ActiveRecord::RecordInvalid error with has_many through association; validation issue on join table


My intuition is that you are over-engineering the validation of the models with that before_add: :validate_description. Are you not served by standard Rails/ActiveRecord methods and conventions? Specifically, validates: true can be set for validation handling between associated models.

Still, there are some gotchas around association validations, and I would recommend reading the following:

EDIT

I got super curious about this and went and replicated the problem, as you described it, via specs (and it's in a public github project). I still think the manual before_add validations are overengineered and I didn't use them, but I am encountering the issue you describe.

So, what I'm trying to understand is whether what you're encountering is expected and desired. Rails is nothing if not opinionated, and maybe using direct setting of has_many-through associations is a sort of coder-beware use case. To be clear, what you're doing is a slightly weird thing: when you ask to set document.product_ids, what you're actually doing is setting matching document_id and product_id on certain description objects. Right? That's weird, and super unclear in intent/expected result.

What's an alternate approach, then? What you're doing is adding descriptions to a document, and those descriptions are on products. Why not, then, interact with the document products through the description interface? That should avoid the has_many-through setter weirdness, and provider a clearer, interface, I think.