Rails: Routing to a different controller based on request format - ruby-on-rails

I'm writing an app where I want all requests for HTML to be handled by the same controller action. I have some other routes that are JSON-specific. Here's what my routes look like:
Blog::Application.routes.draw do
constraints format: :json do
resources :posts
end
match "(*path)" => "web#index"
end
The problem is that constraints is being interpreted as "this route only works with the specified format" rather than "skip this route and try the next one if the request is not in the specified format."
In other words, navigating to /posts in the browser gives me a 406 Not Acceptable because the URL is constrained to the JSON format. Instead, I want it to fall through to web#index if the request is for HTML, and hit the resourceful route if the request is for JSON. How can this be achieved?
(Using Rails 3.2.9.)

I've thought about this, and come to some conclusions.
You might not want all routes to return the single page app HTML, because there are some paths that you'll ideally want to return an HTTP 404 status code from.
Your HTTP routes will be different from your JSON routes
You definitely should be routing different formats to different controllers
It might be advantageous to define all your HTML routes in your Rails router, so that you can use it to generate a javascript router. There is at least one gem that does this
Rails does not have this functionality and this gem https://github.com/svenfuchs/routing-filter doesn't really seem like the right tool. Here is my attempt: Rails routing-filter route all html requests to one action
Having to namespace your JSON API under a module Api to avoid routing collisions is no bad thing.
Don't have content visible to Google on your single page app, or you'll get banned for duplicate content.
I took a slightly different approach, which doesn't really answer the question, but I think it has a few advantages:
Here is my config/routes.rb
FooApp::Application.routes.draw do
# Route all resources to your frontend controller. If you put this
# in a namespace, it will expect to find another frontend controller
# defined in that namespace, particularly useful if, for instance,
# that namespace is called Admin and you want a separate single page
# app for an admin interface. Also, you set a convention on the names
# of your HTML controllers. Use Rails's action_missing method to
# delegate all possible actions on your frontend controllers.
def html_resources(name, options, &block)
resources(name, options.merge(:controller => "frontend"), &block)
end
# JSON API
namespace :api do
resources :things, :except => [:edit, :new]
end
# HTML
html_resources :things, :only => [:edit, :new, :index, :show] do
get :other_action
end
end
class FrontendController < ApplicationController
def action_missing(*args, &block)
render :index
end
end

First of all I think different controllers for the same action is not the "Rails way".
Probably you can solve your problem with low level custom request handler in the middleware.

You can use format in your constraints, e.g.
match '*path', constraints: { path: /foo.*/, format: 'html'}, to: 'home#index', via: [:get]

Related

Should I use resource routing even for non-CRUD routes (Rails)?

Is it considered best practice to use resourceful routes in Rails whenever possible, even if the CRUD verbs don't really match the actions being performed (details follow)?
In my Rails app, I'm implementing an OAuth login system using sorcery's external module. I closely followed their official tutorial, which defines the routes for the OAuth methods like this.
# config/routes.rb
post "oauth/callback" => "oauths#callback"
get "oauth/callback" => "oauths#callback" # for use with Github, Facebook
get "oauth/:provider" => "oauths#oauth", :as => :auth_at_provider
Basically, auth_at_provider is called when the user clicks the "Login via [Provider Name]" button, and the callback is called once they log in via the external provider.
I left the routes as-is, but a teammate reviewing it suggested we use resource routing, like this for example:
resources :oauth only: [:index, :create, :show]
I guess this is technically possible, but for me the singular routes defined in the tutorial are much more intuitive and self-explanatory. So my questions are:
Is it considered better (or common) to use resourceful routes even in cases like this? or
Are resourceful routes just a shorthand for cookie-cutter routes, and should only be used for straightforward controllers?
I wouldn't use the resource(s) helpers. The name tells you it's used for resources and oauth logic are not resources.
You could refactor the routes a little bit though
namespace :oauth do
match :callback, via: [:get, :post]
get ":provider", action: :oauth, as: :at_provider
end
This creates this routes:
oauth_callback GET|POST /oauth/callback(.:format) oauth#callback
oauth_at_provider GET /oauth/:provider(.:format) oauth#oauth
They are basically the same routes, DRYer and without misleading "resource" wording.
*Note the little change from "auth_at_provider" to "oauth_at_provider" introduced by the namespace
It is generally considered best practice to use resourceful routing when you're actually doing CRUD on a resource, ie:
resources :users # for creating, reading, updating, deleting users
If you'd have to create an entirely new resource and controller just for one create endpoint (for example), I don't see any harm in breaking the pattern and using non-resourceful routes, but I try to avoid doing so.
You should try to use resourceful routing with names that makes sense, to keep your routes consistent:
scope path: 'oauth' do
resource :callback, only: [:show, :update] # use show/update instead of callback method
resources :providers, only: [:show] # use show instead of auth_at_provider
end
So your routes would look like:
POST oauth/callback
GET oauth/callback
GET oauth/providers/:id

How are resources connected to controllers without a Model

I am writing a basic application that scrapes data. I have the following in my routes.rb.
Rails.application.routes.draw do
constraints subdomain: 'api' do
namespace :api, path: '/' do
resources :apps, :only => :show
end
end
In controllers I have something like this although I am not sure how are resources connected to Controller.
class AppsController < ApplicationController
def show
puts "this works"
respond_to do |format|
format.json { render json: #user }
end
end
def apps
puts "my app"
end
end
Also, I dont have a Model. Does that mean that in my resources :apps calls a method in AppsController called apps?
If I wanted it t call apps then how's it possible ?
how does a controller in rails know what route does it belong to
I am trying to add a GET /apps?filter=5 that returns my scraped data in the form of JSON and with filter as parameter to that it means that return 5 JSON objects to me
#config/routes.rb
constraints subdomain: 'api' do
namespace :api, path: '/' do
get :apps, to: "apps#apps", on: :collection #-> api.url.com/apps
end
end
A much more coherent way to do it would be...
#config/routes.rb
constraints subdomain: 'api' do
namespace :api, path: '/' do
resources :apps #-> api.url.com/apps -> apps#index
end
end
I think you're getting confused with how Rails works, especially with your data.
I post this all the time, maybe it will help you:
As you can see, your request is not tied to a specific "model", nor is a controller bound to it either. I'll explain the importance of the MVC (Model View Controller) aspect of rails in a minute.
Your thought process is that each request / resource has to have a corresponding model / dataset to pull from. Strictly, this is not the case, although many would believe it to be.
Remember that Rails is just an application framework - it has to work with all the same protocols & restrictions as the other frameworks & languages out there.
When you send a request to Rails (through your browser URL), it takes that request, and matches it to the appropriate controller. This controller action will then pull data from your model (if you've set it up like that), render the view with that data, and return the processed HTML to the browser.
Thus, you don't have to have a model bound to a particular controller action, or anything. You just need to make sure your controllers & views are mapped accordingly.
OOP
I think the part you're getting hooked up on is the object orientated nature of Ruby / Rails.
Although every part of the Rails framework is meant to work with objects, this only applies on a request-basis.
For example, whilst it's typically recommended to keep your controllers resourceful, you don't have to adhere to that methodology if you don't want to. Many newbies don't know the difference.
Thus, when you use the following:
#config/routes.rb
constraints subdomain: 'api' do
namespace :api, path: '/' do
resources :apps, only: :show #-> api.url.com/:id -> apps#show
end
end
... what you're denoting is a controller bound by its resourceful nature. This would typically be expected to use model data, but it's not essential...
In controllers I have something like this although I am not sure how
are resources connected to Controller.
Rails.application.routes.draw provides a DSL which hooks into Rack (the interface between the HTTP server and Rails). It generates rules for where to route the response from Rack.
The DSL is provides has a lot of ways to do the same things. In this example, the resources :apps, :only => :show line basically says you want to generate all of the REST verbs for the AppsController, but you only want the :show verb, so the router will only generate a route to AppsController#show. Note that you can run rake routes to get a list of your routes.
Also, I dont have a Model. Does that mean that in my resources :apps
calls a method in AppsController called apps? If I wanted it t call
apps then how's it possible ?
Models are totally separate abstractions. Once the code reaches your controller you are in plain Ruby land until you return out of that controller action. Models are simply plain Ruby objects with the ability to talk to the database.
In your code if you wanted to call apps from the show method (or action) then you can just call it from there since it's in the same scope.
how does a controller in rails know that ok that is my route. In this case, apps
I'm not sure I understand this question, could you elaborate?
I am trying to add a GET /apps?filter=5 that returns my scraped data in the form of JSON and with filter as parameter to that it means
that return 5 JSON objects to me
For one, you'll need to add a route for /apps. There are several ways you can do this. Here's one approach. I'm going to call it index instead of apps since that's more conventional:
# config/routes.rb
get '/apps' => 'apps#index'
# app/controllers/apps_controller.rb
class AppsController < ApplicationController
respond_to :json
def index
limit = params[:filter].to_i
#users = User.first(limit) # Implement this however you wish
respond_with(#users)
end
end
My syntax might be a little off here with the respond_to and respond_with, but it should explain how the controller routes
Routing simply maps URLs to a controller/action, the existence of a model with the same name does not matter.
To get to the apps action that you defined in the AppsController you need to define a route that maps to apps#apps < This syntax means AppsController, apps action.
An example of a route that would map to the AppsController apps action:
get '/apps', to: "apps#apps"
This is a weird example. It's not conventional to have a def apps action inside AppsController, what exactly are you trying to accomplish with this action?
If you want a rest call to /apps that returns a JSON list of apps, then this all you need to do.
router
resources :apps, only: [:index]
controller
class AppsController < ActionController::Base
def index
puts "This is the index route in AppsController"
end
end
In the router, when you specify resource :apps, only: [:index]. This routes the request GET /apps to AppsController#index

Overriding URL helpers in Rails

I have a Model (Show) in Rails that is accessed via a subdomain rather than a standard REST URL. In the file app/helpers/url_helper.rb I have the following method:
def show_url(show)
root_url(subdomain: show.subdomain)
end
In controllers, this works perfectly. I can test it with puts show_url(#show) and it outputs the subdomain of the show as expected: http://test.example.com. In integration tests, however, the method doesn't work, and the default one generated by rails is used instead. If I run puts show_url(#show) there, I just get http://example.com. How do I use this custom URL helper in my integration tests?
Edit:
routes.rb section regarding this subdomain stuff:
constraints(lambda do |request|
request.subdomain.present? && request.subdomain != 'www'
end) do
get '/' => 'shows#show', as: :show
get '/edit' => 'shows#edit', as: :edit_show
end
This is based loosely around a Railscast on subdomain matching.
Try defining its route without the default "show" action:
# config/routes.rb
resources :show, except: :show
Sounds a bit confusing since your model is called Show, but what it's doing is defining all the standard restful routes (index, new, create, edit, update, delete) except for "show", e.g.
Or another way:
resources :show, only: %w(index new create edit update delete)
I would really consider doing some refactoring and renaming the Show model.

How does a rails resource know to use the show view?

I'm looking at this tutorial: https://www.railstutorial.org/book/sign_up
We get on to rails resources.
config/routes.rb
Rails.application.routes.draw do
root 'static_pages#home'
get 'help' => 'static_pages#help'
get 'about' => 'static_pages#about'
get 'contact' => 'static_pages#contact'
get 'signup' => 'users#new'
resources :users
end
app/controllers/users_controller.rb
class UsersController < ApplicationController
def show
#user = User.find(params[:id])
end
def new
end
end
app/views/users/show.html.erb
<%= #user.name %>, <%= #user.email %>
There is also this handy table of telling us how ruby will handle the various requests to the Users resource.
I have two questions here.
How does RoR know when accessing the /users, /users/1 etc urls, what to actually use the index, show methods.
More importantly, - when the show method is called, how it does it know the give the show.html.erb view to browser? What if I wanted to return a different view?
1. Rails knows which methods to use based on the HTTP request type (GET, POST, PUT, or DELETE) and the endpoint. So when you hit the '/users' endpoint with a GET request, it will use the index method. When you hit the '/users/:id' endpoint with a GET request, it will use the show method.
2. The show.html.erb view is used because the name matches the show method. To use a different view, just use match in the routes file like so:
match "users" => "users#show"
The example above would match the '/users' route to the '/user/:id' route.
The mechanism that is responsible for dispatching actions in response to requests is router. You define all the routes in config/routes.rb file as you said. Each line in this files define the request in clear way. resources is a shorthand to define a set of routes - all of them listed here.
There are two thins that distinct requests - the URL and the HTTP request type (GET, POST, PUT, DELETE). Based on these two things you can clearly direct the request to proper controller. Take a look on this one:
get 'help' => 'static_pages#help'
This means: If you get a request of type get directed to url of value /help dispatch the request to controller static_pages and its action help. What happens in help action is a matter of code.
This is also an answer to your second question, how does Rails know what template should it render. Assume that we still work on above example of help action. If this action has no explicit render call, Rails will use its convention over configuration and search for a template that will be in directory called as the controller and in file name as the action name. Therefore, it will render the file that is in app/views/static_pages/help.html.erb. On the other hand, the developer can call render with explicit other file name, e.g.: render "products/show".
If you want to find more please take a look at these two Rails guides:
Layouts and rendering
Rails Routing
rails is said to have convention over configuaration. this is one of the strongest feature available in Rails.in another way. Smart and less code. Here when u say method name as show. rails by default will look for show.html.erb. if you want to explicitly render some other view. You can do this in your controller methods
render :new_view_name
Regarding the routes.
resources :users
This is very helpful when we have Rest calls ,crud operations.it creates 7 urls for crud. And how it differentiate is depending on http data type.

Rails 3.2 - How to redirect to a namespace?

In a Rails 3.2 application I'm doing I want to create some views (and action handling) specific for mobile devices. So I have created a namespace called mobile.
namespace :mobile do
resources :sessions
resources :areas
end
For example if the user goes to the login page with a mobile I want to use the controller and views I make for that namespace.
So now I have two different ways to login:
new_mobile_session GET /mobile/sessions/new(.:format) mobile/sessions#new
and
new_session GET /sessions/new(.:format) sessions#new
But when a requests comes how could I add the "mobile" namespace to the request if it comes from mobile?
I.e. changing /sessions/new into /mobile/sessions/new
I am using Rack::MobileDetect but I don't know how to use the redirect_to for that purpose.
config.middleware.use Rack::MobileDetect, :redirect_to => '/mobile'
Or should I use a different approach?
Thanks.
You could use a constraint for that.
A Rails routing constraint either is class which responds to matches? or a lambda.
When a constraint is applied to a route, the route will only be considered if the constraint evaluates to true.
Consider this class
class MobileContraint
def matches? request
request.user_agent =~ /Mobile|webOS/
end
end
You can now use this class in the routes like this:
resources :sessions
resources :sessions, :controller=> 'mobile/sessions', :constraints => MobileConstraint.new

Resources