I have the following action in my tags controller:
(params[:q] comes from this plugin http://loopj.com/jquery-tokeninput/)
def index
@tags = Tag.where("name like ?", "%#{params[:q]}%")
results = @tags.map(&:attributes)
@tag = Tag.find_by_name(params[:q])
if @tag.blank?
results << {:name => "Add: #{params[:q]}", :id => "CREATE_#{params[:q]}_END"}
end
respond_to do |format|
format.html
format.json { render :json => results }
end
end
This part:
@tag = Tag.find_by_name(params[:q])
if @tag.blank?
results << {:name => "Add: #{params[:q]}", :id => "CREATE_#{params[:q]}_END"}
end
Makes the line of code above to only trigger if the current tag name doesn’t exist.
The problem is that if the user types something like this in the input:
"programming " <- a trailing white space
" programming" <- a trailing white space
the code is executed anyway, since the trailing spaces makes Rails think that it is a new name.
what’s the best way of dealing with this problem?
You could do:
Note the first line will delete all spaces in the params[:q]. If this is not what you want, you can first duplicate the variable with dup method