Reputation: 1219
I'm confused as to how to sort out routes for my show action. At the moment if I select on a particular guidelines to 'show' it, the url says
/guidelines/1
where 1 is the guideline id
I'd like it to say
/title
(where this is the title of the guideline that is being shown). I'm confused how to manage this in my routes. At the moment my routes has
get 'guideline/:id', to: 'guidelines#show', as: :seeguideline
but this just shows guideline/1 as I mentioned so I realise I'm doing something wrong
My view links to this with
<%= link_to guideline.title, seeguideline_path(id: guideline.id) %>
show action in guidelines_controller.rb is
def show
@guideline = Guideline.where(title: params[:title]).first
respond_to do |format|
format.html # show.html.erb
format.json { render json: @guideline }
end
end
routes are
ActiveAdmin.routes(self)
devise_for :admin_user, ActiveAdmin::Devise.config
get "guidelines/topic"
get "guidelines/topichospital"
get "guidelines/topicspecialty"
get "guidelines/favourite"
devise_for :users
devise_scope :user do
get 'signup', to: 'devise/registrations#new', as: :register
get 'login', to: 'devise/sessions#new', as: :login
get 'logout', to: 'devise/sessions#destroy', as: :logout
get 'edit', to: 'devise/registrations#edit', as: :edit
put 'users' => 'devise/registrations#update', :as => 'user_registration'
get 'about', to: 'about#about', as: :about
end
resources :guidelines
get 'guidelines', to: 'guidelines#index', as: :guidelines
get 'favourites', to: "favourites#show", as: :favourites
get 'topics', to: 'guidelines#list', as: :topics
get 'hospitals', to: 'guidelines#listhospital', as: :hospitals
get 'specialties', to: 'guidelines#listspecialty', as: :specialties
root :to => 'guidelines#index'
get '/:id', to: 'profiles#show', as: :myprofile
get '/:title', to: 'guidelines#show', as: :seeguideline
Upvotes: 3
Views: 5251
Reputation: 2785
You may want to check out this railscast http://railscasts.com/episodes/314-pretty-urls-with-friendlyid
Upvotes: 2
Reputation: 29599
if you want to match urls like '/url', you need to place this at the bottom of your routes file so it takes the least priority (ie it doesnt match '/projects' if you have a projects controller). in theory this is done via
match '/:title' => 'guidelines#show', as: :seeguideline
then in your controller
def show
@guideline = Guideline.where(title: params[:title]).first
end
then in your views, you can use
seeguideline_path(@guideline.title)
but you also have to take care of invalid characters in the title to be used in the url.
Upvotes: 2