I have this form where a user can input tags (tag_list input) like “Graphic design, illustration etc.” I then want to transform these tags in to url friendlt strings, like “graphic-design” before i save them to the database so that i can use them in my html as classes. I’ve gotten it to work where the user only enters one tag into the field, like “Graphic design”, but if the user enters 2 or more fields my code won’t work and i have no idea how to get it to work.
Any ideas?
The model code:
class Work < ActiveRecord::Base
before_save :url_friendly_tags
def url_friendly_tags
self.tag_slug = self.tag_list.to_s.gsub(/\s+/, '_').gsub(/[^\w\-]/, '')
end
end
The view:
<% semantic_form_for @work do |f| %>
<% f.inputs do %>
<%= f.tag_list %>
<%= f.input :tag_slug, :as => :hidden %>
<% end %>
<% end %>
If you want to process a list of tags separated by comma (or semicolon), perhaps you need to
self.tag_list.split(/\s*[;,]\s*/).collect {|s| s.gsub(/\s+/, '_').gsub(/[^\w\-]/, '')}.join(",")or similar (i.e. split the user input before processing)? This should do the trick, provided thatself.tag_listis a string.Previous answer, for the sake of conversation
I misunderstood the problem, so I suggested to use route globbing:
For a url
books/foo/bar/bazthis route will populateparams[:section]with a stringfoo/bar, so you need tosplitit on/.