Hi,
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.
has_and_belongs_to_many :catalogue_categories, :before_add =>
:evaluate_duplicate_category
def evaluate_duplicate_category(catalogue_category)
#check duplicate
#if so raise error and abort add
end
However I am unsure how to abort the add at this stage and return an
error. Could anyone help point me in the right direction?
Thanks,
Andrew.
--
Posted via http://www.ruby-forum.com/.
Is this what you''re looking for? validates_uniqueness_of http://api.rubyonrails.org/classes/ActiveRecord/Validations/ClassMethods.html#M000816 -- Posted via http://www.ruby-forum.com/.
lisa-u wrote:> Is this what you''re looking for? > > validates_uniqueness_of > > http://api.rubyonrails.org/classes/ActiveRecord/Validations/ClassMethods.html#M000816Thanks. 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. -- Posted via http://www.ruby-forum.com/.
Andrew Edwards wrote:> 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 -- Posted via http://www.ruby-forum.com/.