Respond to all HTML requests with layout

2019-06-11 09:18发布

问题:

I'm working on a Rails app that will be using a client-side framework with its own routing feature. I'd like to use pushState routing, so the Rails router will need to be configured to respond to such requests (easy enough).

Is there an easy way to set all HTML requests with a valid route to be responded to with just a layout, without having to clutter up my views folder with a bunch of blank action.html.erb files?

回答1:

Here's a way to intercept requests to valid routes and render a view for every non-ajax request:

app/controllers/application_controller.rb:

class ApplicationController < ActionController::Base
  protect_from_forgery
  before_filter :render_default_view

  # ...

  private

  def render_default_view
    return if request.xhr?
    respond_to do |format|
      format.html { render 'public/default_view.html', :layout => nil }
    end
  end
end

I think this does what you want, right?



回答2:

def my_action
 respond_to do |format|
   format.html { render 'my_unified_view' }
 end