如何在Rails的respond_with中指定":layout => false"?

Lan*_*ard 32 ruby-on-rails

我有这个设置:

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

  def index
    @users = User.all
    respond_with(@users)
  end
end
Run Code Online (Sandbox Code Playgroud)

现在我正试图这样做,如果params[:format] =~ /(js|json)/,render :layout => false, :text => @users.to_json.我如何使用respond_withor respond_to和inherited_resources 做到这一点?

Yan*_*nis 45

就像是:

def index
  @users = User.all
  respond_with @users do |format|
    format.json { render :layout => false, :text => @users.to_json }
  end
end
Run Code Online (Sandbox Code Playgroud)


Ant*_*ric 28

假设您需要JSON来执行Ajax请求

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

  def index
    @users = User.all
    respond_with(@users, :layout => !request.xhr? )
  end
end
Run Code Online (Sandbox Code Playgroud)

这对我来说似乎是最干净的解决方案.


Jer*_*emy 18

或者,为了防止您必须对每个操作中的每种格式进行硬编码.

如果您没有此控制器中任何操作的布局,那么更好:

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

  def index
    @users = User.all
    respond_with(@users)
  end
end
Run Code Online (Sandbox Code Playgroud)


cho*_*eat 8

我喜欢@ anthony的解决方案,但对我不起作用......我必须这样做:

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

ps:发布"回答"而不是评论,因为stackoverflow评论格式和"返回键==提交"是令人愤怒的!


Jon*_*ard 5

我刚刚发现:

即使是JSON,Rails仍在寻找布局。因此,在我们的案例中,它找到的唯一布局是application.html

解决方案:进行JSON布局。

因此,举例来说,如果您在HTML旁边放置一个application.json.erb带有单个= yield内部的空格,那么JSON会更好地处理HTML布局。您甚至可以使用它用元数据或类似内容将JSON包围起来。

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

<%= yield %>
Run Code Online (Sandbox Code Playgroud)

无需其他参数,它可以自动运行!

仅在Rails 4中测试

  • 我刚刚签入了Rails 4.2。如果您将布局文件命名为application.html.slim,则不会将其视为json的布局文件;无论如何,如果您将布局文件命名为`application.slim` ..则它将*被视为JSON的布局文件。(用erb代替slim应该做同样的事情)。 (2认同)