Rails 3 routing - ruby-on-rails-3

Ok, I'm relatively new to rails and am working through the book Rails for PHP programmers. To make things interesting I'm using Rails 3 and haml to work through the book, and the book is written using Rails 2.X and erb so some of the examples are outdated.
To the question:
The route example in the book is
map.presentation 'meetings/:meeting_id/presentations/:action/:id',
:controller => "presentations",
:action => "show",
:meeting_id => /\d+/
So that was a pre-Rails 3 route. My adaptation of the above into a Rails 3 route is:
match 'meetings/:meeting_id/presentations/:action/:id', :to => 'presentations#show', :constraints => {:id => /\d/}
My adaptation works for the destroy action, but not for the edit action... and due to my inexperience I don't know what I'm doing wrong. From the article here (http://www.engineyard.com/blog/2010/the-lowdown-on-routes-in-rails-3/) it looks like I'm doing it right, but something isn't right.
The link_to helpers that produce the urls are as follows
= link_to 'edit', :controller => 'presentations',
:action => 'edit',
:meeting_id => presentation.meeting.id,
:id => presentation.id
# Incorrectly Produces: http://localhost:3000/presentations/edit?meeting_id=2&id=1
= link_to 'destroy', { :controller => 'presentations',
:action => 'destroy',
:meeting_id => presentation.meeting.id,
:id => presentation.id },
:confirm => 'Are you sure?',
:method => :delete
# Correctly Produces: http://localhost:3000/meetings/2/presentations/destroy/1
Your help would go a long way to clearing up my routing haziness. Thanks so much!
EDIT
Here's the non-working routes.rb file in its entirety:
UserGroup::Application.routes.draw do
get "presentations/new"
get "presentations/edit"
get "sessions/new"
get "users/index"
get "users/show"
get "users/new"
get "users/edit"
get "meetings/index"
match '/meetings/show/:id', :to => 'meetings#show', :as => 'meeting'
match '/meetings/new', :to => 'meetings#new', :as => 'new_meeting'
match '/meetings/edit/:id', :to => 'meetings#edit', :as => 'edit_meeting'
match 'meetings/:meeting_id/presentations/:action/:id', :to => 'presentations', :constraints => {:id => /\d/}
#default route
match ':controller(/:action(/:id(.:format)))'
end
EDIT 2
Thanks to codykrieger I took a look at the rest of the routes file (I know, duh right?). Apparently, all those get "..." routes are added when using the rails generator and help to make some default connections in the app. I commented out the get "presentations/edit" line and, wonder of wonders, my routing adaptation actually does work.
This works:
UserGroup::Application.routes.draw do
get "presentations/new"
#get "presentations/edit"
get "sessions/new"
get "users/index"
get "users/show"
get "users/new"
get "users/edit"
get "meetings/index"
match '/meetings/show/:id', :to => 'meetings#show', :as => 'meeting'
match '/meetings/new', :to => 'meetings#new', :as => 'new_meeting'
match '/meetings/edit/:id', :to => 'meetings#edit', :as => 'edit_meeting'
match 'meetings/:meeting_id/presentations/:action/:id', :to => 'presentations', :constraints => {:id => /\d/}
#default route
match ':controller(/:action(/:id(.:format)))'
end
I played around with the order of the routes in the file and also found that if I put my route above all the auto-generated routes, without commenting out the get "presentations/edit" line, my route still has the intended effect.
This also works:
UserGroup::Application.routes.draw do
match 'meetings/:meeting_id/presentations/:action/:id', :to => 'presentations', :constraints => {:id => /\d/}
get "presentations/new"
get "presentations/edit"
get "sessions/new"
get "users/index"
get "users/show"
get "users/new"
get "users/edit"
get "meetings/index"
match '/meetings/show/:id', :to => 'meetings#show', :as => 'meeting'
match '/meetings/new', :to => 'meetings#new', :as => 'new_meeting'
match '/meetings/edit/:id', :to => 'meetings#edit', :as => 'edit_meeting'
#default route
match ':controller(/:action(/:id(.:format)))'
end
I'm thinking that the latter is the better way to go and I should make my custom routing declarations above the standard generated ones, but I'm not sure. If someone out there wants to comment on which practice is better, or if it's better to entirely remove the generated ones if I want to specify my own, I'd love to hear it.
Thanks all :)

Routing is done on a first match basis (top to bottom) in the routes.rb file.
So you can keep all routes as you have done above if you want, and Rails will use the first one that matches. However, its messy, potentially buggy and totally unnecessary. So the "match..." lines in your code should be enough, and you can remove the "get..." lines.
Furthermore, your "match...presentations...." line has a bug, it should be
...{:id => /\d+/}
else it will validate only 1-digit length ids.
Finally, as far as your overall routes.rb is concerned, you do not need to do
link_to 'edit', :controller => 'presentations',
:action => 'edit',
:meeting_id => presentation.meeting.id,
:id => presentation.id
Instead, you should use edit_meeting_path, new_meeting_path etc. For instance
<%= link_to "New meeting", new_meeting_path %>
<%= link_to "Edit meeting", edit_meeting_path(#meeting) %>
Finally, you should read Rails Routing from the Outside In for best practices on how to design nested routes etc.

Related

Update users details without a password by admin. Rails 3.x Devise

I would like to create a link to approve a users signup,
1) First solution<%= link_to "Approve", edit_user_registration_path(:id => user.id, :approved => true), :method => :put %>
However it drops back No route matches [PUT] "/users/edit"
2) Also I was thinking about an extra action that will respond to a specific route and update the user signup, say match '/users/approve_user', :controller => 'users', :action => 'approve_user', :collection => { :my_action => :put}
and in the view:
%- link_to "Approve", users_approve_user_path(:id => user.id), :method => :put
However, it gives back that Couldn't find User with ID=approve_user
Any help will be appreciated
I think you should use custom routing with devise
This is direct from devise documentation (https://github.com/plataformatec/devise), configuring routes
devise_scope :user do
get "sign_in", :to => "devise/sessions#new"
end
so in your case try something like
devise_scope :user do
post "Approve", :to => "users/approve_user"
end
and please note, by default device users controller comes under the name space 'devise'.

Using generated paths with resources in Rails

I have following routes defined:
CyberTrackRails3::Application.routes.draw do
scope "(:locale)", :locale => /en|de|nl/ do
resources :login do
get 'index', on: :collection
get 'check', on: :collection
end
end
end
Now, url_for(:controller => 'login', :action => 'check'), gives me the correct url, en/login/check.
Using login_check_path however doesn't work. How do I make this work?
I've tried replacing get 'index', on: :collection with match 'check' => 'check' but that doesn't work. Neither does match 'check' => 'login#check'.
since you're adding an action to a resource, i think the automatically generated name is going to be reversed, ie 'check_logins_path' (see adding-more-restful-actions)
do you need login_check_path specifically? if so, you should be able to define the path outside of the resources :login block, ie
match '/login/check' => 'login#check', :via => :get, :as => 'login_check'
and like Fivell suggested, rake routes will show you the automatically generated name for a route.

Change password with RESTful authentication

OK, I've been having relative success with RESTful authentication. I followed this tutorial to add the capability to change the password. The problem is that tutorial is written for rails 2.3 and I'm using rails 3.
The code used in my controller and view are exactly as they are in the tutorial
I added to routes.rb:
match '/change_password' => 'users#change_password', :as => :change_password
resources :users, :controller => 'users', :collection => {:change_password_update => :put}
Now i get this error: undefined method `change_password_update_user_path'
the comments to the tutorial mentioned that exact error, and they said the solution is in the routing, but given the routing differences between 2.3 and 3, I'm really just guessing what needs to go in there. Any idea how i can get this working?
all i had to do is change
<% form_tag change_password_update_user_path(current_user), :method => :put do |f| %>
to
<% form_tag '/change_password_update', :method => :put do |f| %>
and put this in my routes.rb
match '/change_password' => 'users#change_password', :as => :change_password
match '/change_password_update' => 'users#change_password_update', :as => :change_password_update
resources :users, :controller => 'users', :collection => {:change_password_update => :put}

Trying to create a POST request but getting No route matches [GET]

I'm trying to do something similar to Railscasts #255 but I'm getting a No Route error:
In Ryan's routes.rb file:
post "versions/:id/revert" => "versions#revert", :as => "revert_version"
In in the controller where he uses the route, versions_controller.rb
link = view_context.link_to(link_name, revert_version_path(#version.next, :redo => !params[:redo]), :method => :post)
redirect_to :back, :notice => "Undid #{#version.event}. #{link}"
In my routes.rb
post "/approve/:id" => "listings#approve", :as => "listing_approve"
and view where I use my link:
<%= link_to 'Approve Content', listing_approve_path(#listing), :method => :post %>
My tests return to me a ActionController::RoutingError: No route matches [GET] "/approve/1"
If I leave the method as a GET everything works.. Using rails 3.1.0rc5. Any guidance as to what I'm doing wrong here would be very much appreciated..
EDIT: routes.rb file (the last line is set as match right now to work)
RLR::Application.routes.draw do
root :to => "home#index"
devise_for :users, :controllers => { :registrations => "registrations" }
devise_for :users
match '/user' => "layouts#index", :as => :user_root
resources :users, :only => :show
resources :layouts, :only => [:index, :show]
resources :listings
resources :features
resources :orders
match "/preview/:id" => "listings#preview", :as => "listing_preview", :via => "get"
match "/approve/:id" => "listings#approve", :as => "listing_approve"
end
Hmmmm, it looks right to my eye. The test sounds like it is generating a GET instead of a POST though, so it might be a problem with the link_to call. You've got :method => :post there, so it should be fine. http://api.rubyonrails.org/classes/ActionView/Helpers/UrlHelper.html#method-i-link_to seems to indicate that link_to will generate some javascript to make a POST call on click (and that users with javascript disabled will get a normal GET link unless you use :href="#"), so it might be because your test engine isn't running the javascript.
You can fix this by changing it to a button that submits a hidden form, but that might not be the visual representation you want.
It might be a precedence thing - the first matching route definition in routes.rb is used, so if you have a resources route or something like that it may be matching on that first.
I got the same problem in my rails application and I solved it the same way you did by doing a via: :get on the match instead of a via: :post. I think for some reason when you send a request in the format of /something/:id it will automatically assume its a [GET] request and search for a get route. This of course will cause problems in your routes if you have it as a :POST.
If anyone has a better solution or idea as to why you cannot send a post request in the format '/something/:id' let me know please.

Better way to route this?

I have a routing issue. my routes currently look like this:
http://localhost:3000/events?category=popular&city=london&country=united-kingdom
Currently its just looking at resources :events (which is the events controller, index action), and in the index action. I've got a lot of if conditions. Especially, when the app needs to determine which partials to load, based on the query strings.
Is there a better way to refactor this? I am not a big fan of query strings in the URL. And something like this can be solved in routing. Just looking for the right direction. Am looking to have urls like:
/events/london
/events/london/popular
/events/london/united-kingdom
/events/united-kingdom
/events/united-kingdom/popular
/events/london/united-kingdom/popular
The Anti Patterns book, specifically on page 181, suggests creating separate controllers. Which will organize the code further and still keep it RESTFUL.
In theory, I think it is suggesting something like this:
match 'events/:city', :controller => 'events/cities', :action => 'index', :as => 'by_city', :via => :get
match 'events/:city/:category', :controller => 'events/cities_and_categories', :action => 'index', :as => 'by_city_and_category', :via => :get
match 'events/:city/:country', :controller => 'events/cities_and_countries', :action => 'index', :as => 'by_city_and_country', :via => :get
match 'events/:country', :controller => 'events/countries', :action => 'index', :as => 'by_country', :via => :get
match 'events/:country/:category', :controller => 'events/countries_and_categories', :action => 'index', :as => 'by_country_and_category', :via => :get
match 'events/:city/:country/:category', :controller => 'events/cities_and_countries_and_categories', :action => 'index', :as => 'by_city_and_country_and_category', :via => :get
OR, are filtered terms REALLY supposed to be in query string format?
If you have a suggestions / better approach. Do mention.
First off, some cleaner routes that are more canonical:
resources :events do
get '/:country(/:city)(/:category)' => 'events#filtered', :on => :collection, :constrain => { :category => %w{ popular legal_marijuana } }
end
I've made the country required. There are too many ambiguous city names, and unless you want to do a lot of poking to determine segment is what, this is just more straightforward. The city is optional, and so is the category.
Unless I've mistaken something here, this will constrain the category to either "popular" or "legal_marijuana" (but not both, so Amsterdam is out, haha).
All of these routes go to a single filtered action on your events controller. Don't bother trying to keep this resourceful unless it makes sense for every country and city to be a resource for your application. As long as this responds to a GET request, and it retrieves a collection of records, it's not very far out of the bounds of the REST principals (interesting note, the new and edit actions in Rails don't adhere strictly to REST either).
This action will need to do a bit of poking at params to see whether or not you have a city or category. You can use something like this to help you out:
#event = Event.where(:country => params[:country])
#event = #event.where(:city => params[:city]) if params[:city]
[For some reason this doesn't look right to me. I can't think straight. I'm sure that this is a mess. Someone please save me.]
But yeah, that's the idea.