I am trying to restrict duplicate has_and_belongs_to_many associations.
I tried to find support for a association validation for duplicates but
couldn’t find anything.
I understand I could use :uniq=>true on the model association but this
would only prevent it from displaying duplicates, I want to stop
duplicate associations being inserted in the first place.
I have a vague idea of something using a callback to check before
adding.
I had looked at this but thought it would only be useful where the
association is represented by a physical model.
In my system products and categories are linked, but just by a plain
habtm association with a join table that has no corresponding model. If
I gave the association a physical model I probably could use the
validates_uniqueness_of within that model but at this stage such a model
is otherwise not neccesary.
If I have misunderstood its capability let me know.
I had looked at this but thought it would only be useful where the
association is represented by a physical model.
In my system products and categories are linked, but just by a plain
habtm association with a join table that has no corresponding model.
You do need a table categories_products that contains category_id and
product_id to store the link in the case of HABTM. (Btw, tablea_tableb
should be in alphabetical order.) Although HABTM by itself does not
require you to generate a model, to validates_uniqueness_of, you need
the Category_Product model (I’m not 100% sure about the naming
convention in this case)
If you really want to avoid making this table, use has_many/belongs_to
relationships. And validates_uniqueness_of category with scope
product_id
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.