2016-03-06 67 views
0

我对Ruby on Rails非常陌生,在设计和实现REST API方面是全新的。我有一个运行,并试图做一个简单的发布请求,通过curl保存在我的数据库中的东西。Ruby on Rails - 测试REST API时发布的请求被拒绝?

这里是我的路线:

GET /api/v1/employees(.:format)       api_employees#index 
    POST /api/v1/employees(.:format)       api_employees#create 
    GET /api/v1/employees/:id(.:format)      api_employees#show 
    PUT /api/v1/employees/:id(.:format)      api_employees#update 
    GET /api/v1/employees/:id/addresses(.:format)    api_addresses#index 
    POST /api/v1/employees/:id/addresses(.:format)    api_addresses#create 
    GET /api/v1/employees/:id/addresses/:address_id(.:format) api_addresses#show 
    PUT /api/v1/employees/:id/addresses/:address_id(.:format) api_addresses#update 

,这里是我的api_employees控制器。我还没有创建地址控制器,但我试图发布一个员工。

class ApiEmployeesController < BaseApiController 
before_filter :find_employee, only: [:show, :update] 

before_filter only: :create do 
    unless @json.has_key?('employee') && @json['employee']['address'] 
    render nothing: true, status: :bad_request 
    end 
end 

before_filter only: :update do 
    unless @json.has_key?('employee') 
    render nothing: true, status: :bad_request 
    end 
end 

before_filter only: :create do 
    @employee = Employee.find_by_id(@json['employee']['id']) 
end 

def index 
    render json: Employee.all 
end 

def show 
    render json: @employee 
end 

def create 
    if @employee.present? 
    render nothing: true, status: :conflict 
    else 
    @employee = Employee.new 
    @employee.assign_attributes(@json['employee']) 
    if @employee.save 
     render json: @employee 
    else 
     render nothing: true, status: :bad_request 
    end 
    end 
end 

def update 
    @employee.assign_attributes(@json['employee']) 
    if @employee.save 
    render json: @employee 
    else 
    render nothing: true, status: :bad_request 
    end 
end 

private 
    def find_employee 
    @employee = Employee.find_by_id(params[:id]) 
    render nothing: true, status: :not_found unless @employee.present? 
    end 
end 

我尝试使用后:卷曲-H “内容类型:应用程序/ JSON” -X POST -d '{ “员工”:{ “地址”: “123.123.123.123”}}' http://myapi.heroku.com/api/v1/employees

和我得到的回应

<body> 
<!-- This file lives in public/422.html --> 
<div class="dialog"> 
    <div> 
    <h1>The change you wanted was rejected.</h1> 
    <p>Maybe you tried to change something you didn't have access to.</p> 
    </div> 
    <p>If you are the application owner check the logs for more information.</p> 
</div> 

我需要以某种方式改变访问?任何帮助深表感谢。

回答

2

Just needed skip_before_action:verify_authenticity_token