我试图告诉Rails 3.2默认渲染JSON,并完全禁用HTML,代码如下:
respond_to :json
def index
@clients = Client.all
respond_with @clients
end
使用这个语法,我必须在URL中添加.json
。 我该如何实现?
我试图告诉Rails 3.2默认渲染JSON,并完全禁用HTML,代码如下:
respond_to :json
def index
@clients = Client.all
respond_with @clients
end
使用这个语法,我必须在URL中添加.json
。 我该如何实现?
routes.rb
文件来指定默认格式。
routes.rbresources :clients, defaults: {format: :json}
这将修改整个clients_controller
的默认响应格式。
如果您想要在Web和API上使用相同的控制器操作,那么这种模式非常适合。像往常一样制作Web版本,使用:html作为默认格式。然后将API放在一个路径下,并在那里设置:json为默认格式。
Rails.application.routes.draw do
resources :products
scope "/api", defaults: {format: :json} do
resources :products
end
end
如果您的索引操作不需要RESTful响应,则可以直接呈现您的XML响应:
def index
render json: Client.all
end
index
操作根本不应该响应 html,而且你希望它即使在 URL 中没有 .json 也能响应 json。 - jdoeRails.application.routes.draw do
scope '/', defaults: { format: :json } do
resources :products
end
end
devise_for:users,defaults:{format::json}
。 - Bibek Shrestha
defaults format: 'json' {resources :clients; resources :products}
。 - Tony - Currentuser.ionamespace :api, { defaults: { format: :json } } do
。我目前正在Rails 5上这样做。 - Ryan