Lets say I have a Page resource, and a particular instance has id = 5 and permalink = foobar.
With resources :pages I can use <%= link_to #page.title, #page %> which outputs the url "/pages/5".
How would I make it output "/pages/foobar" instead? Likewise with the edit url... How do I make edit_page_path(#page) output "/pages/foobar/edit"?
UPDATE
Answers so far have said to override to_param in Page.rb which is a great start. +1 to each. But what if I want <%=link_to #page.title, #page%> to output "/:permalink" rather than "/pages/:permalink"?? I'll accept the answer that comes up with that.
You can override the to_param method in your model which will tell Rails what to use instead of your primary key for routing.
For example
class Page
def to_param
"#{self.id}-#{self.title.parameterize}"
end
end
The parameterize call makes your title URL friendly, you might also notice the use of self.id, this is recommended in case you have a duplicate title.
You need to overide to_param method in your model to return the field you want. Here's a blog post with some examples:
You want to use a permalink.
Add this to your model:
class Post
def to_param
"#{id}-{title}"
end
end
This assumes that you have a title.
Once you get this you want to look look up permalink-fu, or it's actually really simple to do your own with an after save:
class Post
before_save :manage_peramlink
def manage_peramlink
permalink = "#{name.gsub(/\s/, '_').gsub(/[^\w-]/, '').downcase}"
end
def to_param
"permalink"
end
end
Make sure you add peramlink as a field to your model.
Related
I'm trying to setup slugs to have urls like this:
/artists/1/pink-floyd
My to_param method is:
def to_param
"#{self.id}/#{self.name.parameterize}"
end
Unfortunately url is /artists/1%2Fpink-floyd
How can I make this work the way I want?
You can do this a number of ways.
I think what would be the closest to what you want to achieve is something like:
def to_param
"#{self.id}-#{self.name.parameterize}"
end
Which makes:
/artists/1-pink-floyd
An alternative would be to change the routes:
get "/artists/:id/:parameterized_name" => "artists#show", as: :artist
This will give you params :parameterized_name in your controller action.
To use it in the view:
artist_path(artist, parameterized_name: artist.name.parameterize)
I have models that looks like
search.rb:
id eg: 101
name eg: San Francisco
cars.rb
id
name
The search controller redirects user to cars.
search_controller.rb
if search.search_type=='cars'
redirect_to :controller=>'cars', :action=>'index', :id=>search
end
A query to find list of cars from San Francisco looks like:
http://localhost/cars?id=101
I overrode to_param method in search.rb like:
search.rb
def to_param
normalized_name = name.gsub(' ', '-').gsub(/[^a-zA-Z0-9\_\-\.]/, '')
"#{self.id}-#{normalized_name}"
end
This works to some extent:
It generates URLs that look like:
http://localhost/cars?id=101-San-Francisco
However, I would like is to generate a URL that looks like
http://localhost/cars/San-Francisco
How would I go about doing that?
Do I fix the routes?
Thanks for your help.
This can be tricky if you're not prepared for it. The method that controls how a model shows up in the params is pretty straightforward, as you've identified, but that's only the half of it. Later you'll have to retrieve it, so you need to set up for that:
class Search < ActiveRecord::Base
before_save :assign_slug
def self.from_param(id)
self.find_by_slug(id)
end
def to_param
self.slug
end
protected
def assign_slug
self.slug = self.name.gsub(' ', '-').gsub(/[^\w\-\.]/, '')
end
end
This requires adding a slug column to your Search model in order to make it possible to look up a search by it. It may be a good idea to add an index, possibly a unique one, to help retrieve these later in an efficient manner.
In your controller you don't use find but from_param instead to do the retrieval.
You'll also need to add a custom route that takes this parameter:
match '/cars/:search', :to => 'cars#index', :as => 'cars_search'
As a note you should use the route path generator methods whenever possible because multiple routes may match the same parameters. For instance:
redirect_to cars_search_path(:search => search)
I understand how to create a vanity URL in Rails in order to translate
http://mysite.com/forum/1 into http://mysite.com/some-forum-name
But I'd like to take it a step further and get the following working (if it is possible at all):
Instead of:
http://mysite.com/forum/1/board/99/thread/321
I'd like in the first step to get to something like this: http://mysite.com/1/99/321
and ultimately have it like http://mysite.com/some-forum-name/some-board-name/this-is-the-thread-subject.
Is this possible?
To have this work "nicely" with the Rails URL helpers you have to override to_param in your model:
def to_param
permalink
end
Where permalink is generated by perhaps a before_save
before_save :set_permalink
def set_permalink
self.permalink = title.parameterize
end
The reason you create a permalink is because, eventually, maybe, potentially, you'll have a title that is not URL friendly. That is where parameterize comes in.
Now, as for finding those posts based on what permalink is you can either go the easy route or the hard route.
Easy route
Define to_param slightly differently:
def to_param
id.to_s + permalink
end
Continue using Forum.find(params[:id]) where params[:id] would be something such as 1-my-awesome-forum. Why does this still work? Well, Rails will call to_i on the argument passed to find, and calling to_i on that string will return simply 1.
Hard route
Leave to_param the same. Resort to using find_by_permalink in your controllers, using params[:id] which is passed in form the routes:
Model.find_by_permalink(params[:id])
Now for the fun part
Now you want to take the resource out of the URL. Well, it's a Sisyphean approach. Sure you could stop using the routing helpers Ruby on Rails provides such as map.resources and define them using map.connect but is it really worth that much gain? What "special super powers" does it grant you? None, I'm afraid.
But still if you wanted to do that, here's a great place to start from:
get ':forum_id/:board_id/:topic_id', :to => "topics#show", :as => "forum_board_topic"
Take a look at the Rails Routing from the Outside In guide.
maybe try something like
map.my_thread ':forum_id/:board_od/:thread_id.:format', :controller => 'threads', :action => 'show'
And then in your controller have
#forum = Forum.find(params[:forum_id])
#board = #forum.find(params[:board_id])
#thread = #board.find(params[:thread_id])
Notice that you can have that model_id be anything (the name in this case)
In your view, you can use
<%= link_to my_thread_path(#forum, #board, #thread) %>
I hope this helps
I am currently developing a blogging system with Ruby on Rails and want the user to define his "permalinks" for static pages or blog posts, meaning:
the user should be able to set the page name, eg. "test-article" (that should be available via /posts/test-article) - how would I realize this in the rails applications and the routing file?
for user-friendly permalinks you can use gem 'has_permalink'. For more details http://haspermalink.org
Modifying the to_param method in the Model indeed is required/convenient, like the others said already:
def to_param
pagename.parameterize
end
But in order to find the posts you also need to change the Controller, since the default Post.find methods searches for ID and not pagename. For the show action you'd need something like this:
def show
#post = Post.where(:pagename => params[:id]).first
end
Same goes for the other action methods.
You routing rules can stay the same as for regular routes with an ID number.
I personally prefer to do it this way:
Put the following in your Post model (stick it at the bottom before the closing 'end' tag)
def to_param
permalink
end
def permalink
"#{id}-#{title.parameterize}"
end
That's it. You don't need to change any of the find_by methods. This gives you URL's of the form "123-title-of-post".
You can use the friendly_id gem. There are no special controller changes required. Simple add an attribute for example slug to your model..for more details check out the github repo of the gem.
The #63 and #117 episodes of railscasts might help you. Also check out the resources there.
You should have seolink or permalink attribute in pages' or posts' objects. Then you'd just use to_param method for your post or page model that would return that attribute.
to_param method is used in *_path methods when you pass them an object.
So if your post has title "foo bar" and seolink "baz-quux", you define a to_param method in model like this:
def to_param
seolink
end
Then when you do something like post_path(#post) you'll get the /posts/baz-quux or any other relevant url that you have configured in config/routes.rb file (my example applies to resourceful urls). In the show action of your controller you'll just have to find_by_seolink instead of find[_by_id].
How do I get the to_param method to deliver keyword slugs all the time? I have trouble getting it to work with this route:
map.pike '/auction/:auction_id/item/:id', :controller => 'items', :action => 'show'
Earlier the overridden to_param was working for
'items/1-cashmere-scarf'
but fails with 'auction/123/item/1'
Update:
I'm not sure if the syntax is correct[(edit: it's correct: it works :-)], or even efficient.... but using haml, I found that the following code works to generate the desired link ('auction/:auction_id/item/:id')
- for auction in #auctions.sort{|a, b| a.scheduled_start <=> b.scheduled_start}
-for item in #items
- unless auction.current_auction
... pike_path(auction.auction_id, item)
I'm not sure whether I understand your question. (it's 3:41 AM here)
From what I see, you directly access auction_id method, instead of using pike_path(auction, item) that'd use #to_param.
Also, it might fail for auction/123/item/1 because you haven't changed your controller.
I think it'd be helpful to describe how to get working slugs.
Broadly speaking, if you override #to_param, IDs no longer works. It means, that if you go with slugs, every time polymorpic URL is generated (eg, link_to object, object), it passes to_param's value. It is worth noting that you must change your controller as well.
Personally I think that the best way to generate slugs easily is to use techno-weenie's permalink_fu, adding has_permalink to your model, and then, override to_param. For example
class Auction < ActiveRecord::Base
has_permalink :title, :slug
end
assuming that you have slug, a string field, and want to slugize your title.
You also need to adjust your controller:
class AuctionsController < ApplicationController
def show
#auction = Auction.find_by_slug(params[:id]) || raise(ActiveRecord::RecordNotFound)
respond_to do |format|
format.html # show.html.erb
end
end
Then, you can generate routes, in the views, this way:
link_to #action, #action
By the way, you should NOT sort your actions in the view. The best way is to use named_scope.