roYal
roYal

Reputation: 197

Filtering string in Rails

I have this method that will add tags to db.

def all_tags=(names)
  self.tags = names.split(",").map do |name|
    Tag.where(name: name.strip).first_or_create!
  end
end

It takes a string and strip it where there is a comma and add each string in db. The problem is that a user can add duplicate tags ex 'red, blue, red'.

How can i check that user can't add tags that have the same name or remove the duplicate.

Upvotes: 0

Views: 74

Answers (1)

Albert Paul
Albert Paul

Reputation: 1218

Use uniqueness validator in your Tag model.

class Tag < ActiveRecord::Base
  validates :tag, uniqueness: true
end

http://guides.rubyonrails.org/active_record_validations.html#uniqueness

Upvotes: 1

Related Questions