Ruby-on-rails 默认呈现 JSON 而不是 HTML?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10681816/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 03:25:28  来源:igfitidea点击:

Render JSON instead of HTML as default?

ruby-on-railsruby-on-rails-3rendering

提问by trnc

I try to tell rails 3.2 that it should render JSON by default, and kick HTML completely like this:

我试图告诉 rails 3.2 它应该默认呈现 JSON,并像这样完全踢 HTML:

respond_to :json    

def index
  @clients = Client.all
  respond_with @clients
end

With this syntax, I have to add .jsonto the URL. How can I achieve it?

使用此语法,我必须添加.json到 URL。我怎样才能实现它?

回答by rogeliog

You can modify your routes.rbfiles to specify the default format

您可以修改routes.rb文件以指定默认格式

routes.rb

路由文件

resources :clients, defaults: {format: :json}

This will modify the default response format for your entire clients_controller

这将修改您的整个默认响应格式 clients_controller

回答by jdoe

If you don't need RESTful responding in your index action then simply render your xml response directly:

如果您在索引操作中不需要 RESTful 响应,那么只需直接呈现您的 xml 响应:

def index
  render json: Client.all
end

回答by Mark Swardstrom

This pattern works well if you want to use the same controller actions for both. Make a web version as usual, using :html as the default format. Then, tuck the api under a path and set :json as the default there.

如果您想对两者使用相同的控制器操作,则此模式非常有效。像往常一样制作网络版本,使用 :html 作为默认格式。然后,将 api 放在路径下并将 :json 设置为默认值。

Rails.application.routes.draw do

  resources :products

  scope "/api", defaults: {format: :json} do
    resources :products
  end

end