开发者

Rails 3 - Tidying Up Tags?

I'm having an issue with article Tags where a user can write an article once they have signed-in and add tags to the bottom of the article... pretty standard stuff.

Am using the .titleised method which works fine, however I notice that if a user enters 3 tags without commas it then displays all these words as a single tag.开发者_Go百科

Is there a way I can automatically enter a comma after each word 'on submit' before they are entered into the db via the model even if the user doesn't ?

For example: Red, Hot, Roof, instead of Red Hot Roof

models/article.rb

def assign_tags
if @tag_names
  self.tags = @tag_names.split(/\,/).map do |name|
    Tag.find_or_create_by_name(name.titleize)

models/tag.rb

class Tag < ActiveRecord::Base

attr_accessible :name
validates :name, :uniqueness => true

# order by creation
default_scope :order => 'created_at DESC'

has_many :taggings, :dependent => :destroy  
has_many :articles, :through => :taggings
end


Just change

self.tags = @tag_names.split(/\,/).map do |name|

to

self.tags = @tag_names.split(/[\,\s]/).reject(&:blank?).map do |name|

thus splitting at commas AND whitespaces, and then removing any empty strings, and you should be fine.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜