Can you help me convert this route to rails 3? - ruby-on-rails

I read a few websites and questions but all were far beyond my level except one site:
http://markconnell.co.uk/posts/2010/02/rails-3-routing-examples
I'm trying to follow Head First Rails which was made for Rails 2 and so far it's been going well enough. I've been able to find the conversions so far, this is really the first place since installation to stump me.
It says in the config/routes.rb file that it should read:
ActionController::Routing::Routes.draw do |map|
map.connect '/ads/:id', :controller=>'ads', :action=>'show'
map.connect ':controller/:action/:id'
map.connect ':controller/:action/:id.:format'
end
First off my routes.rb file defaults that first line to be
Mebay::Application.routes.draw do
So my first attempt read:
Mebay::Application.routes.draw do
map.connect '/ads/:id', :controller=>'ads', :action=>'show'
map.connect ':controller/:action/:id'
map.connect ':controller/:action/:id.:format'
end
When that failed I tried this:
Mebay::Application.routes.draw do'
map '/ads/:id' => 'ads#index'
end
Then I tried the same thing but adding |map| to the first line.
And finally, I tried changing it all to this:
ActionController::Routing::Routes.draw do |map|
map '/ads/:id' => 'ads#index'
end
None of these have worked though. Could someone please help me out here, I'm not sure what I'm doing wrong. I have another book, Ruby On Rails 3 by Hartl but in the Index it doesn't even show anything on Routes so don't even know where to look in there.
Thanks for any help you can offer me!
// EDIT - I also tried with it reading '/ads/':id thinking perhaps that is a mistake since it doesn't make sense to me why :id would be inside quotes.
// EDIT 2 - This is what Rake Routes returns:
WARNING: 'require 'rake/rdoctask'' is deprecated. Please use 'require 'rdoc/task' (in RDoc 2.4.2+)' instead.
at /Users/Dennis/.rvm/gems/ruby-1.9.2-p318#rails3tutorial/gems/rake-0.9.2.2/lib/rake/rdoctask.rb
WARNING: Global access to Rake DSL methods is deprecated. Please include
... Rake::DSL into classes and modules which use the Rake DSL methods
WARNING: DSL method Mebay::Application#task called at /Users/Dennis/.rvm/gems/ruby-1.9.2-p318#rails3tutorial/gems/railties-3.0.1/lib/rails/application.rb:214:in `initialize_tasks'
/ads/:id(.:format) {:controller=>"ads", :action=>"show"}
/:controller/:action/:id(.:format)
/:controller/:action/:id.:format
Error Message:
Routing Error
No route matches "/ads/3"
//EDIT 3 - This is what my 2 controller files look like:
ads_controller:
class AdsController < ApplicationController
end
application_controller:
class ApplicationController < ActionController::Base
protect_from_forgery
end
//EDIT 4 -
Tried in the ads_controller.rb file:
class AdsController < ApplicationController
def show;
end
end
Also tried in the same file:
class AdsController < ApplicationController
end
def show;
end
And each way I tried going to
localhost:3000/mebay/ads/3
localhost:3000/ads/3
localhost:3000/show/ads/3
localhost:3000/mebay/show/ads/3
Same error still "Routing Error. No Route Matches..."

ActionController::Routing::Routes.draw do
match '/ads/:id' => 'ads#show'
match ':controller/:action/:id'
match ':controller/:action/:id.:format'
end
I thoroughly recommend reading the docs: http://apidock.com/rails/ActionDispatch/Routing

I also am using that book and going through for a difference between rails 2 and rails 3.
I got this to work. In routes.rb file all you need to do is add this between the do and the end:
resources :ads
The key is that your routes.rb file is only sending that resource to the right spot. The next place to look is the ads_controller.rb file where you will want to add this:
#Get /ads/1
#Get /ads/1.json
def show
#ad = Ad.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.json { render json: #ad }
end
end
The next part is adding the index which is a bit later in that chapter. You'll want to add this above that:
# GET /ads
# GET /ads.json
def index
#ads = Ad.all
respond_to do |format|
format.html # index.html.erb
format.json { render json: #ad }
end
end
Basically if you look at the chapter 1 routes.rb and controller files you'll see that scaffold configures a rails 3 app like that. One more thing that confused me was I was only able to get the javascript to work by putting it in /app/assets/stylesheets and editing application.html.erb and setting the stylesheet link to look like this:
<%= stylesheet_link_tag "application", :media => "default.css" %>
Enjoy

If you are using Rails 3 you don't want to do a Rails 2 tutorial. There are plenty of good rails 3 tutorials out there. For your question about routes, see the blog post below which might help you figure it out.
http://gregmoreno.wordpress.com/2010/08/12/rails-3-upgrade-part-2-routes/

Try making this your Routes file. I had the same problem while doing it from Chapter 2 of Head First Rails. But this resolved it for me
Mebay::Application.routes.draw do
controller 'ads' do
match 'ads/:id' => :show
end
end

Related

`redirect_to #article` throws the `NoMethodError in Blog::ArticlesController#create` error

I am trying to go through the 'Ruby on Rails Getting Started' tutorial(guides.rubyonrails.org) and I am running into this issue I cannot seem to figure out. I reached the point in the tutorial where I can create an article, but the redirect to see the article immediately after creation does not work and I get an error that says:
NoMethodError in Blog::ArticlesController#create
undefined method `article_url' for #<Blog::ArticlesController:0x00007f814841af20>
Here is my article controller code:
class Blog::ArticlesController < ApplicationController
def new
#article = Article.new
end
def create
#article = Article.new(params.require(:article).permit(:title, :category, :text))
#article.save
redirect_to #article # <-- This line throws error
end
def show
#article = Article.find(params[:id])
end
end
and here is my routes.rb (omitted irrelevant code):
Rails.application.routes.draw do
# <-- other get functions here
get 'blog', to: 'blog#index'
namespace :blog do
resources :articles # <-- Suggestions were to make these plural
end
root 'about#index'
end
The only deviation I have done from the tutorial is that I wanted to place the articles in a name space, as well as 1 extra value to enter in the form(category). The only suggestions for fixing my issue when I searched was to make resource into plural but my code already has this and to add #article = Article.new into def new in the controller but this addition made no difference.
I found a work around that will properly redirect after creating a new article that is the line as follows:
redirect_to :action => "show", :id => #article.id
But this doesn't seem like the "Rails Way"(Convention over Configuration), and I really don't understand why the suggested code in the tutorial is not working for me
The Rails-ey way to redirect to the proper route would be to first check in the terminal with rails routes.
There you will see if you want to route to articles#show under the namespace blog that the prefix (first column) is blog_article.
You can use this prefix with the _path method like so:
redirect_to blog_article_path(#article)

Rails Take all actions in the controllers in area

In my rails application I add an "api" area with controllers
In the route.rb file
I add the area
namespace :api do
#get "dashboard/sales_rate"
end
The controllers Class:
class Api::DashboardController < Api::ApplicationController
before_filter :authenticate_user!
def user_service
render :json => {"user_id" => current_user.id}
end
The Path is:
app/controllers/api/dashboard_controller
My question is if I can that the route take all action
for example /api/dashboard/user_service
and I will not add for each route row on the route.rb page
/api/{controller_under_api_namespace}/{action}
You can do with some meta programming sprinkle!
Api.constants.each |c|
c.action_methods.each do |action|
get [c.controller_name, action].join('/')
end
end
This method limits only to GET request. You can overcome it with RESTful routing.
Api.constants.each |c|
resources c.controller_name.to_sym
end
Hope, that helps. :)
I try add the code on the route.rb file
and I got this error
This is my file
But before trying to fix this part of code, I want to know if it's can change the performance or the calls to those pages?
If it not good for the performance I leave this option.

Rails 3.2 error routing issue. Error ID is conflicting with other object ID

We just upgraded our app to Rails 3.2.2 and are now having a routing issue for handling errors.
Per José Valim's blog post, we added the following:
config.exceptions_app = self.routes to config/application.rb
match "/404", :to => "errors#not_found" to config/routes.rb
(and the appropriate controller/views).
The problem is we need ourdomain.com/id to display an index page for a product category of id.
So, now ourdomain.com/404 shows our 404 page, when it should show our category listing page for the category with an id of 404.
How can we work around this?
Is there a way to make the app prepend each error with error_ before it's evaluated by routes?
Or, maybe somehow set config.exceptions_app to reference a namespace in the routes file?
Or, can I create a second route set and set config.exceptions_app = self.second_set_of_routes?
Thanks!
We had the same problem -- error codes colliding with ids for resources at the root level (e.g., collisions between ourdomain.com/:resource_id and ourdomain.com/404).
We modified José Valim's solution by adding a route constraint that only applies when handling an exception:
# Are we handling an exception?
class ExceptionAppConstraint
def self.matches?(request)
request.env["action_dispatch.exception"].present?
end
end
MyApp::Application.routes.draw do
# These routes are only considered when there is an exception
constraints(ExceptionAppConstraint) do
match "/404", :to => "errors#not_found"
match "/500", :to => "errors#internal_server_error"
# Any other status code
match '*a', :to => "errors#unknown"
end
...
# other routes, including 'match "/:resource_id"'
end
(We only stumbled on this solution last night, so it hasn't had much burn-in time. We are using Rails 3.2.8)
There's one solution which I've found so far:
# application_controller.rb
def rescue_404
rescue_action_in_public CustomNotFoundError.new
end
def rescue_action_in_public(exception)
case exception
when CustomNotFoundError, ::ActionController::UnknownAction then
#render_with_layout "shared/error404", 404, "standard"
render template: "shared/error404", layout: "standard", status: "404"
else
#message = exception
render template: "shared/error", layout: "standard", status: "500"
end
end
def local_request?
return false
end
rescue_action_in_public is the method that Rails calls to handle most errors.
local_request? the method tells Rails to stop sucking if it's local request
# config/routes.rb
match '*path', controller: 'application', action: 'rescue_404' \
unless ::ActionController::Base.consider_all_requests_local
It simply says that it can’t find any other route to handle the request (i.e. the *path) it should call the rescue_404 action on the application controller (the first method above).
EDIT
This version worked for me well!
Try to add to application.rb
# 404 catch all route
config.after_initialize do |app|
app.routes.append{ match '*a', to: 'application#render_not_found' } \
unless config.consider_all_requests_local
end
See: https://github.com/rails/rails/issues/671#issuecomment-1780159
It seems that this route is hard coded at the show_exceptions method (see source)
Sorry, but I don't think of a way of doing it besides changing the line 45 on the source above to:
env["PATH_INFO"] = "/error_#{status}"
(what is, needless to say, no solution at all).
It doesn't hurt to ask:If you thought it was nice to have your own error controller implemented so simply and desperately want to have it, than wouldn't it even be more "RESTful" if your route were yourdomain.com/product/:id?

Rescue from routing error rails 3.1

How to rescue from RoutingError in rails 3.1 application. If i'm nt mistaken it was possible to use rescue_from RoutingError in application controller but now it's not possible.
There is no great way to handle it, but there are a few workarounds. The discussion here yields the following suggestion:
Routes
Add the following to your routes file:
match "*", :to => "home#routing_error"
and handle the error in this action:
def routing_error
render text: "Not found, sorry", status: :not_found
end
I wasn't able to replicate #matthew-savage's results. However, per the Rails guide on route globbing and this question on another StackOverflow question, I solved this issue like so:
routes.rb
match "*gibberish", :to => "home#routing_error"
notice how I included text after the wildcard. The controller is fine as shown above:
controller/home_controller.rb
....
def routing_error
render text: "Not found, sorry", status: :not_found
end
Good example.
route.rb
Rails 3:
match '*unmatched_route', :to => 'application#raise_not_found!'
Rails 4:
get '*unmatched_route' => 'application#raise_not_found!'
application_controller.rb
def raise_not_found!
raise ActionController::RoutingError.new("No route matches #{params[:unmatched_route]}")
end

Is it possible to change the default action for a RESTful resource?

In Ruby on Rails, is it possible to change a default action for a RESTful resource, so than when someone, for example, goes to /books it gets :new instead of the listing (I don't care if that means not being able to show the listing anymore)?
I'd point out that if you are pointing /books to /books/new, you are going to be confusing anyone who is expecting REST. If you aren't working alone, or if you are and have other come on board later, or if you expect to expose an API to the outside, the REST convention is that /books takes you to a listing, /books/new is where you create a new record.
Not sure why would you do such a thing, but just add this
map.connect "/books", :controller => "books", :action => "new", :conditions => { :method => :get}
to your config/routes.rb before the
map.resources :books
and it should work.
Yes. You should be able to replace your index method in your controller...
def index
#resource = Resource.new
# have your index template with they proper form
end
In the same vein, you can just do
def index
show
end
def index
redirect_to new_book_path
end
I think would be the simplest way.

Resources