Validates_uniqueness_of with habtm

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

Les N. 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

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 forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs