Rails 4:ActiveRecords无法从JSON保存数据

时间:2016-04-15 23:13:24

标签: ruby-on-rails json

我正在尝试从我在服务器上发送的JSON请求中保存数据。我已经为 CSRF 后卫添加了例外,它会传递请求。 ActiveRecords 不会保存数据,但它适用于HTML请求。

我使用 curl 生成JSON请求

curl  -v -X POST -d '{"claim": {"lastname":"Jhon Smith","phone":"+1(51)555555","latitude":"10.4","longitude":"12.7","theme":"Test message","text":"Text of test message"}}'  -H "Content-Type:application/json" -H "Accept:application/json" http://localhost:3000/claims/new

它返回消息代码200。

> POST /claims/new HTTP/1.1
> Host: localhost:3000
> User-Agent: curl/7.43.0
> Content-Type:application/json
> Accept:application/json
> Content-Length: 167
> 
* upload completely sent off: 167 out of 167 bytes
< HTTP/1.1 200 OK 
< X-Frame-Options: SAMEORIGIN
< X-Xss-Protection: 1; mode=block
< X-Content-Type-Options: nosniff
< Content-Type: application/json; charset=utf-8
< Cache-Control: no-cache
  

服务器回答说它抓住了数据但没有做任何事情。

Started POST "/claims/new" for 127.0.0.1 at 2016-04-16 01:35:24 +0300
Processing by ClaimsController#new as JSON
  Parameters: {"claim"=>{"lastname"=>"Jhon Smith", "phone"=>"+1(51)555555", "latitude"=>"10.4", "longitude"=>"12.7", "theme"=>"Test message", "text"=>"Text of test message"}}
  Rendered claims/new.json.erb (0.0ms)
Completed 200 OK in 2ms (Views: 1.2ms | ActiveRecord: 0.0ms)

我的控制器的代码试图保存 JSON

def create
  @claim = Claim.new(claim_params)

  respond_to do |format|
    if @claim.save
      format.html do
        redirect_to acceptedclaim_path
        flash[:success] = "Ваша заява прийнята! Дякуємо за допомогу!"
      end
      format.json do
        render json: @claim, status: :created, location: @claim
      end
    else
      format.html do
        redirect_to new_claim_path
        flash[:danger] = flash_errors(@claim)
      end
      format.json do
        render json: @claim.errors, status: :unprocessable_entity
      end
    end
  end
end

def claim_params
  params.require(:claim).permit(:lastname, :phone, :latitude, :longitude, :theme, :text)
end

我通过路由器中的下一个配置访问POST

post   'claims/new' => 'claims#new'

我将不胜感激任何帮助!

1 个答案:

答案 0 :(得分:1)

POST /claims/new正在点击您控制器中的new操作,但在您的示例中,您定义了create操作。

要修复此问题,请将其添加到您的路线中(如果该路线尚不存在):

post 'claims' => 'claims#create'

使用相同的参数来定位POST /claims动作。

相关问题