开发者

Splitting the value of an input and making the results url-friendly

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 that self.tag_list is a string.

Previous answer, for the sake of conversation

I misunderstood the problem, so I suggested to use route globbing:

match 'books/*section/:title' => 'books#show'

For a url books/foo/bar/baz this route will populate params[:section] with a string foo/bar, so you need to split it on /.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜