Forum: Ruby on Rails validates_uniqueness_of with habtm

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
A0eee794e60f2555d410b8accb674ffb?d=identicon&s=25 Les Nightingill (lazylester)
on 2006-04-05 02:25
it's a blog...

class Entry < ActiveRecord::Base
  has_and_belongs_to_many :categories
end

similarly:

class Category < ActiveRecord::Base
  has_and_belongs_to_many :entries
end

I wish to make sure that the owner doesn't add the same category to a
given entry more than once... I'm thinking that validates_uniqueness_of
should be usable here. But can't figure out how to include it.

ideas?

thanks
69bc2439b61e69b372caae8f3affe653?d=identicon&s=25 Bryan Buecking (Guest)
on 2006-04-05 04:09
(Received via mailing list)
Les Nightingill wrote:
> end
>
> I wish to make sure that the owner doesn't add the same category to a
> given entry more than once... I'm thinking that validates_uniqueness_of
> should be usable here. But can't figure out how to include it.
>
> ideas?
>
Here's one way...

entry.categories << category unless entry.categories.include?(category)

not sure if that's what you're looking for..
--
Bryan Buecking
A0eee794e60f2555d410b8accb674ffb?d=identicon&s=25 Les Nightingill (lazylester)
on 2006-04-05 04:16
Bryan Buecking wrote:
> Here's one way...
>
> entry.categories << category unless entry.categories.include?(category)
>
> not sure if that's what you're looking for..
> --
> Bryan Buecking

That'll work well, Bryan, I had something similar but not as clean. I
was trying to see if there was a way to use validates_uniqueness_of. I
guess not though, because I'm sure you would've spotted it.

thanks for taking the time to help, Bryan

Les
This topic is locked and can not be replied to.