Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
454 views
in Technique[技术] by (71.8m points)

ruby on rails - Creating url slugs for tags with acts_as_taggable_on

I would like to create url slugs for tags managed by the acts_as_taggable_on gem. For instance instead of urls like http://myapp.com/tags/5, I would like to have http://myapp.com/tags/my-tag (where 'my tag' is the tag's unique name).

In models that I create myself I usually do this by overriding the model's to_param method, and creating a "slug" field in the model to save the result of the new to_param method. I tried doing this with the Tag model of ActsAsTaggableOn, but it is not working.

I can otherwise override things in the tag.rb class of ActsAsTaggableOn as follows:

# Overwrite tag class
ActsAsTaggableOn::Tag.class_eval do
  def name
    n = read_attribute(:name).split
    n.each {|word| word.capitalize!}.join(" ")
  end      
end

However, if I try to override the to_param method in that same block with a method definition like:

def to_param
  name.parameterize
end

Rails still generates and responds to routes with integer IDs rather than the parameterized name. In fact in the console if I try something like

ActsAsTaggableOn::Tag.find(1).to_param

The integer ID is returned, rather than the result of the overridden to_param method.

I'd rather not fork the gem and customize it if there is any way I can do it with my own application code. Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I'm using the friendly_id ( https://github.com/norman/friendly_id ) gem to manage slugs. My method to create slugs for my tags is similar to yours, but a lit bit simpler.

I've just created the initializer act_as_taggable_on.rb with the following code:

# act_as_taggable_on.rb
ActsAsTaggableOn::Tag.class_eval do
  has_friendly_id :name,
                  :use_slug => true,
                  :approximate_ascii => true,
                  :reserved_words => ['show', 'edit', 'create', 'update', 'destroy']
end

And then:

@user = User.new :name => "Jamie Forrest"
@user.tag_list = "This is awesome!, I'm a ruby programmer"
@user.save

And voilá:

ActsAsTaggableOn::Tag.find('this-is-awesome')    #=> #<Tag id: 1, name: "This is awesome!">
ActsAsTaggableOn::Tag.find('im-a-ruby-programmer')    #=> #<Tag id: 2, name: "I'm a ruby programmer">

Hope this help...


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...