ezio ezio - 3 months ago 7
Ruby Question

Ruby on Rails: Can someone help me with this? Trying to create a record by passing json through an API and it's not working

So I have a server model and I am trying to populate the table by passing json through a POST request in POSTMAN. But it inserts null value for all the attributes. Here's a the folder structure


the folder structure

railsApp
app
controllers
api
v1
servers_controller.rb


This is the servers_controller.rb file

class Api::V1::ServersController < ApplicationController

protect_from_forgery
skip_before_action :verify_authenticity_token, if: :json_request?


def json_request?
request.format.json?
end

def index
puts params.inspect
@servers = Server.all
render :json => @servers
end

def show
@server = Server.find(params[:id])
render :json => @server
end

def create
puts params.inspect
@server = Server.new(server_params)
@server.save

respond_to do |format|
format.json {render :json => @server}
end
end

private

def server_params
params.require(:server).permit(:url, :name) if params[:server]
end
end


Here's the json request:

{
"server": {
"url" : "www.google.com",
"name": "Google"
}
}


And this is the record that is being inserted

{
"id": 57,
"url": null,
"name": null,
"created_at": "2016-08-16T14:45:23.207Z",
"updated_at": "2016-08-16T14:45:23.207Z",
"server_id": null,
"cluster_id": null
}


After researching stackoveflow, I found this: ActionController::ParameterMissing (param is missing or the value is empty: film): But this is not working. Can anyone help with this? Thanks

edit: This is the output in the rails console.


Started POST "/api/v1/servers" for ::1 at 2016-08-16 11:42:16 -0400
Processing by Api::V1::ServersController#create as JSON
(0.2ms) BEGIN
SQL (8.7ms) INSERT INTO "servers" ("created_at", "updated_at") VALUES ($1, $2) RETURNING "id" [["created_at", 2016-08-16 15:42:16 UTC], ["updated_at", 2016-08-16 15:42:16 UTC]]
(0.8ms) COMMIT
Completed 200 OK in 14ms (Views: 1.1ms | ActiveRecord: 9.6ms)

</pre>

Answer

The error is in your request headers I think . You should send your request with headers indicating them as json . so you will need to send along this header as well . Content-Type: application/json

Comments