Reputation: 42
I am trying to save data from JSON request that I am sending on my server. I already added exceptions to CSRF defender and it passes requests. ActiveRecords doesn't save data from it, but it does for HTML requests.
I use curl to generate JSON requests
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
It returns message code 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
Server answered that it caught data but didn't do anything.
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)
There is code of my controller that trying to save 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
I access POST via next config in router
post 'claims/new' => 'claims#new'
I will be grateful for any help!
Upvotes: 2
Views: 40
Reputation: 11235
POST /claims/new
is hitting the new
action in your controller, but in your example you defined the create
action.
To fix, add this to your routes if it isn't already present:
post 'claims' => 'claims#create'
And target the POST /claims
action with the same params.
Upvotes: 1