简体   繁体   中英

Rails routes: json endpoint naming convention

I have an endpoint that renders json:

def controller_method
   render json: json_response
end

However, I am curious about the naming convention of the route. The following naming leads to ActionController::UnknownFormat Controller#controller_method is missing a template for this request format and variant. :

get '/controller/controller_method.json', to: 'controller#controller_method'

However, I successfully get the json when the route is named:

get '/controller/controller_method_data', to: 'controller#controller_method'

Am I not allowed to put .json in the url routes? Any way that I can allow .json be the name of the route?

There is a much easier way to respond to different formats - just use ActionController::MimeResponds

get '/controller/controller_method', to: 'controller#controller_method'
class Controller < ApplicationController
  def controller_method
    respond_to do |format|
      format.json { render json: { hello: 'world' } }
      format.html # renders the view implicitly
      format.txt { render plain: 'Hello world'}
    end
  end
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM