开发者

What if I have an API method and a contoller/view method with the same name in RoR?

开发者 https://www.devze.com 2022-12-25 15:33 出处:网络
Suppose I want to be able to view a list of products on my site by going to /product/list. Great. So this uses my \'list\' view and outputs some 开发者_JAVA百科HTML which my web browser will render.

Suppose I want to be able to view a list of products on my site by going to /product/list. Great. So this uses my 'list' view and outputs some 开发者_JAVA百科HTML which my web browser will render.

But now suppose I want to provide a REST API to my client where they can get a list of their products. So I suppose I'd have them authenticate with oAuth and then they'd call /product/list which would return a JSON array of their products.

But like I said earlier, /product/list displays an HTML web page. So, I have a conflict.

What is normal practice as far as providing APIs in Rails? Should I have a subdirectory, 'api', in /app/controller, and another 'product' controller? So my client would go to /api/product/list to get a list of their products?

I'm a bit new to RoR, so I don't have the best grasp of the REST functionality yet, but hopefully my question makes sense.


the common practice is to use respond_to method. You can have one controller to render HTML web page, JSON or XML response.

class StatesController < ApplicationController
  def index
    @states = State.get_states_by_country(params[:country_id])

    respond_to do |format|
        format.html
        format.json { render :json => { :prompt => t('address.select_state'),
                                        :states => @states.to_json(:only => [:id], :methods => [:name]) }}
        format.js
    end
  end
end


Using the respond_do it's actually quite easy: http://weblog.jamisbuck.org/2006/3/27/web-services-rails-style

Then they can just go to products/list/index.json and be good to go.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号