Using :uniq in has_and_belongs_to_many (habtm)
class Stock < ActiveRecord::Base
has_and_belongs_to_many :portfolios
end
class Portfolio < ActiveRecord::Base
belongs_to :user
has_and_belongs_to_many :stocks
end
So, I was running into the problem of checking to see if a stock was already in a portfolio. After digging around thru .find for habtm, .include? for arrays, and such, I found that I could just specify the portfolio model like this:
class Portfolio < ActiveRecord::Base
belongs_to :user
has_and_belongs_to_many :stocks, :uniq => true
end
It works! No more pain for unique entries!


Riley
June 11, 2006 at 11:41 PM
Doesn’t this only work on retrieved objects? ie you can still insert duplicate portfolios_stocks, they just won’t be retrieved. Do you know if there is a way to prevent duplicate inserts (without having to manually lookup if it already exists).
miguelgodinho.com
June 11, 2006 at 11:41 PM
create a composite index in migration file, following the same example:
add\_index :portfolios\_stocks, [:portfolio\_id, :stock\_id], :unique => true
not very elegant, as one will have to deal with runtime exceptions, but probably the fastest and most reliable way.