Rails 3.1/Mongoid - How to find model by name rather than id in routes
Edit: i am using Mongoid/MongoDB for my database, meaning I don't get the normal Active Record tools I think.
I have a simple Rails 3.1 app with a model Page. I would like to match '/:customURL' to the Page#show action for the Page with the relevant :customURL. How should I change the controller and routes? Keep in mind that there are a few routes from '/SOMETHING' that I 开发者_如何学运维want to keep. For instance '/pages' should still go to my Page#index action not try to find a page with customURL of 'pages'.
current controller:
def show
@page = Page.find(params[:id])
@title = @page.title
respond_to do |format|
format.html # show.html.erb
format.json { render json: @page }
end
end
routes:
resources :pages do
resources :feeds
end
get "pages/index"
get "pages/show"
get "pages/new"
root :to => "pages#index"
Thanks a million.
Assuming that your Page
has a customURL
attribute from its database table. In your controller:
def show
@page = Page.first(:conditions => {:customURL => params[:customURL]})
@title = @page.title
respond_to do |format|
format.html # show.html.erb
format.json { render json: @page }
end
end
In your routes
resources :pages, :except => :show do
resources :feeds
end
# Anything you want to match before the custom URLs needs to go above the next route definition
get "/:customURL" => "pages#show"
root :to => "pages#index"
精彩评论