2013-09-29 38 views
0

我已經編寫了一個簡單的API,但是有關路由和API的感覺錯誤。這是我第一次編寫一個API,並且只需幾個月就可以編寫ROR代碼。看看下面的代碼,並幫助我理清它!具有子域的API的路由

我希望API響應請求像https://api.xxxxx.com/v1/xml?username=u_name&password=passwd&到= XXXXX &從XXXX =消息& =文本

的子域似乎並不奏效要麼;

路線

namespace :api, :path => "", constraints: {subdomain: 'api'} do 
namespace :v1 do 
    namespace :json, defaults: {format: :json} do 
    resources :messages 
    resources :balance 
    end 

    namespace :xml, defaults: {format: :xml} do 
    resources :messages 
    resources :balance 
    end 

end 

end 

這些是JSON API

消息控制器控制器:

class Api::V1::Json::MessagesController < ApplicationController 
before_filter :authenticate 


def show 

end 

def create 
    @user = current_user 
    @message = Message.new(params[:message]) 
    if @message.save 
     MessageWorker.perform_async(@message.id, lists, current_user.id) 
     render json: {status: "success", to: @message.count, from: @message.from, 
        balance: @user.balance, message: @message.message}, 
        time: @message.created_at} 
    else 
     render status: 400 
    end 
end 


def authenticate 
    authenticate_or_request_with_http_basic do |username,password| 
     resource = User.find_by_email(username) 
     if resource.valid_password?(password) 
     sign_in :user, resource 
     end 
    end 
end 

end 

平衡控制器:

class Api::V1::Json::BalanceController < ApplicationController 
before_filter :authenticate 


def show 
    @balance = current_user.balance 
    render json: {user: current_user.name.titleize, balance: "#{current_user.currency}: #{@balance}"} 

end 

def authenticate 
    authenticate_or_request_with_http_basic do |username,password| 
     resource = User.find_by_email(username) 
     if resource.valid_password?(password) 
     sign_in :user, resource 
     end 
    end 
end 

end 

回答

1

務必:

constraints subdomain: 'api' do 
    scope module: :api do 
    namespace :v1 do 

你寧願不命名空間JSON或XML,它沒有任何意義:相同的控制器應該處理這兩個請求,只是格式的問題。 Rails使它非常容易與respond_to