Rails 3: how to use gsub or to replace whitespace characters with "-"?
I have an Artist model is name:string. and I want /u开发者_C百科sers/1/artists/jimi-hendrix/posts instead of what I have now which is /users/1/artists/1/posts
The problem is I don't think I can use friendly_id for the artist's name, this is because I have multiples of the same artist name but I want to use the same slug, such as jimi-hendrix for all 'jimi hendrix' entries. Example:
/users/3/artists/jimi-hendrix/posts
/users/55/artists/jimi-hendrix/posts
/users/106/artists/jimi-hendrix/posts
Friendly_id makes it looks like this: (which I can't have) /users/3/artists/jimi-hendrix/posts /users/55/artists/jimi-hendrix--2/posts /users/106/artists/jimi-hendrix--3/posts
So what I'm thinking of doing is passing that artist name parameter to the controller instead of the id. But I need to take the name and replace all whitespace with "-" and then add back the whitespace in the controller correct?
This woulds be my link: (can you doing something like artist.name.gsub!() ??)
<% @artists.each do |artist| %>
<%= link_to artist.name, user_artist_posts_path(@user, artist.name) %>
<% end %>
Then reverse it when I get the code back to the controller?
def index @name = params(:artist_id).gsub() # ? @posts = ... .... end
Or would anyone know how to have non-unique slugs in friendly_id, so it doesn't append the --2, --3 if the attribute has a duplicate name?
To gsub anything that is a non-word-character:
@name = params[:artist_id].gsub( /\W/, '-' )
You should be able to use scoped friendly_id's for this.
This is available in both friendly_id 3.x and 4.x.
eg: in friendly_id 3.x you can do
has_friendly_id :name, :use_slug => true, :scope => :user
and in 4.x
extend FriendlyId
friendly_id :name, :use => :scoped, :scope => :user
If your user_id is 55, your find statements should then be User.find(55).artists.find(params[:id])
for example. OR Artist.find(params[:id]).where(:user_id => 55)
.
Without seeing other code you may have (routes / models / has_many / belongs_to relationships) I can't give you an exact answer.
FriendlyId 4.x docs http://rubydoc.info/github/norman/friendly_id/master/frames
FriendlyId 3.2.1.1 Guide https://github.com/norman/friendly_id/blob/a9505acb68c56719d8225ccb09b5840e26be2783/Guide.md
精彩评论