How do I specify “:layout => false” in Rails' respond_with?

后端 未结 7 1859
星月不相逢
星月不相逢 2020-12-13 18:37

I have this setup:

class UsersController < InheritedResources::Base
  respond_to :html, :js, :xml, :json

  def index
    @users = User.all
    respond_wi         


        
相关标签:
7条回答
  • 2020-12-13 18:53

    Assuming you need JSON for an Ajax request

    class UsersController < InheritedResources::Base
      respond_to :html, :js, :xml, :json
    
      def index
        @users = User.all
        respond_with(@users, :layout => !request.xhr? )
      end
    end
    

    This seems like the cleanest solution to me.

    0 讨论(0)
  • 2020-12-13 18:53

    You need to set this on your show action.

    def show
      render :layout => !request.xhr?
    end
    

    :)

    0 讨论(0)
  • 2020-12-13 18:58

    I love @anthony's solution, but didn't work for me... I had to do:

    respond_with(@users) do |format|
      format.html { render :layout => !request.xhr? }
    end
    

    ps: posting an "answer" instead of a comment because stackoverflow comment formatting and "return key == submit" is infuriating!

    0 讨论(0)
  • 2020-12-13 18:59

    Something like:

    def index
      @users = User.all
      respond_with @users do |format|
        format.json { render :layout => false, :text => @users.to_json }
      end
    end
    
    0 讨论(0)
  • 2020-12-13 19:07
    class UsersController < InheritedResources::Base
      layout -> (controller) { controller.request.xhr? ? false : 'application' }
    end
    
    0 讨论(0)
  • 2020-12-13 19:08

    I just found this out:

    Even if it's JSON, Rails is still looking for a layout. As such, the only layout that it finds, in our case, is application.html.

    Solution: Make a JSON layout.

    So for instance, if you put an empty application.json.erb with a single = yield inside, next to your HTML one, the HTML layout is bettered by the JSON one. You can even use this to surround your JSON with metadata or things like that.

    <%# app/views/layouts/application.json.erb %>
    
    <%= yield %>
    

    No other parameters needed, it automagically works!

    Tested in Rails 4 only

    0 讨论(0)
提交回复
热议问题