Mik*_*ike 36 ruby resources routes dry ruby-on-rails-3
我的路线中定义了资源.
resources :categories
Run Code Online (Sandbox Code Playgroud)
我的类别控制器中有以下内容:
def show
@category = Category.find(params[:id])
respond_to do |format|
format.json { render :json => @category }
format.xml { render :xml => @category }
end
end
Run Code Online (Sandbox Code Playgroud)
控制器动作适用于json和xml.但是,我不希望控制器响应html格式请求.我怎么才能只允许json和xml?这应该只在show动作中发生.
实现这一目标的最佳方法是什么?还有什么好的提示来干掉respond_to块吗?
谢谢你的帮助.
Mik*_*ike 41
我发现这似乎有效(感谢@Pan指出我正确的方向):
resources :categories, :except => [:show]
resources :categories, :only => [:show], :defaults => { :format => 'json' }
Run Code Online (Sandbox Code Playgroud)
以上似乎强制路由器默认为json,为show动作提供无格式请求.
koo*_*nse 36
如果要将这些路由限制为特定格式(例如html或json),则必须将这些路由包装在作用域中.遗憾的是,在这种情况下,约束条件无法正常工作.
这是这样一个块的一个例子......
scope :format => true, :constraints => { :format => 'json' } do
get '/bar' => "bar#index_with_json"
end
Run Code Online (Sandbox Code Playgroud)
更多信息可以在这里找到:https://github.com/rails/rails/issues/5548
这个答案是从我之前的答案复制而来的.
Pan*_*kos 24
您可以在routes.rb文件中执行以下操作,以确保只将show动作约束为json或xml:
resources :categories, :except => [:show]
resources :categories, :only => [:show], :constraints => {:format => /(json|xml)/}
Run Code Online (Sandbox Code Playgroud)
如果这不起作用,您可以尝试显式匹配操作:
resources :categories, :except => [:show]
match 'categories/:id.:format' => 'categories#show', :constraints => {:format => /(json|xml)/}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
27033 次 |
最近记录: |