Api request not working on development mode - ruby-on-rails

I have rails app and i have event controller
def create
#event = Event.create(event_params)
#event.location_id = Location.find_by_address(params[:address]).id
#event.owner = current_user
if params[:clot_id].present?
#event.clot_id = params[:clot_id]
end
render json: #event, status: 201, location: #event
end
def event_params
params.require(:event).permit(:venue, :clot_id, :contact, :cost, :description, :name, :tag_list,:location_id,
compound_started_at_attributes: [:date, :time],
compound_ended_at_attributes: [:date, :time], location_attributes: [:id, :address])
end
When i try to make curl request on localhost its working fine
curl -i -H 'Authorization: Token token'="NXNW8kxzZ2z8czHF6" -X POST -d 'event[venue]=indore&event[contact]=9977966105&event[cost]=52&event[name]=forencis&event[compound_started_at_attributes][date]= 2015-08-20&event[compound_started_at_attributes][time]= 09.05&event[compound_ended_at_attributes][date]= 2015-08-25&event[compound_ended_at_attributes][time]= 10.05&event[location_id]=10&event[clot_id]=26' http://localhost:3000/api/events
curl to server
curl -i -H 'Authorization: Token token'="oKSMrppRXEiRSH61okn5" -X POST -d 'event[venue]=indore&event[contact]=9977966105&event[cost]=52&event[name]=forencis&event[compound_started_at_attributes][date]= 2015-08-20&event[compound_started_at_attributes][time]= 09.05&event[compound_ended_at_attributes][date]= 2015-08-25&event[compound_ended_at_attributes][time]= 10.05&event[location][address]=indore&event[clot_id]=1' 104.236.233.57/api/events
But when i m trying to make same curl request to production server its giving error in production.log
F, [2015-07-02T14:20:47.041280 #29752] FATAL -- :
NoMethodError (undefined method `id' for nil:NilClass):
app/controllers/api/events_controller.rb:34:in `create
i.e error in line
#event.location_id = Location.find_by_address(params[:address]).id
I checked the database for the presence of location_id = 10 in production database and i also checked other values in database before sending api request.
Please help me solve the error.

you're using the :address param and in the query string, address is inside location param: event[location][address]=indore.
Shouldn't be event[address]=indore?
And your code assumes that always 'Location' will be found. You shouldn't assume that and add some validation to Event class (or other workaround that makes sense to you):
#event.location_id = Location.find_by_address(params[:address]).try(:id)
And in Event class:
class Event
validates_presence_of :location_id
end

Related

Upload document using grape api | ArgumentError (missing keyword: io)

I am trying to upload image using grape api. I have done the following steps.
rails active_storage:install
rails g model user name email avatar:attachment
rails db:migrate
module API
module V1
class Users < Grape::API
include API::V1::Defaults
desc 'Create User'
params do
requires :name, type: String, desc: "User name"
requires :email, type: String, desc: "User email"
requires :avatar, :type => Rack::Multipart::UploadedFile, :desc => "Image file."
end
put "/user" do
binding.pry
User.create(params)
return {status: 'success'}
end
end
end
end
But I am getting the following error,
ArgumentError: missing keyword: io
from /Users/nnnn/.rbenv/versions/2.6.0/lib/ruby/gems/2.6.0/gems/activestorage-6.1.4/app/models/active_storage/blob.rb:97:in `build_after_unfurling'
Help me to fix this issue.
curl command to hit the server.
[![curl --location --request PUT 'localhost:3000/api/v1/user' \ --header 'Cookie: __profilin=p%3Dt' \ --form 'avatar=#"/Users/nnnn/Downloads/1623340316453.jpeg"' \ --form 'name="Tester"' \ --form 'email="tester#gmail.com"'][1]][1]

500 Server Error when making post request with httparty

Im trying to reproduce the following request using httparty:
curl --verbose --data '{"username":"my_user#mail.com", "password":"my_password"}' http://my_page/api/user/authenticate
This is what I'm doing:
class RequestParty
include HTTParty
def initialize(base_uri)
self.class.base_uri base_uri
end
def post(endpoint, options)
self.class.post(endpoint, options)
end
end
RequestParty.new("http://my_page/api").post("/user/authenticate",{"username" => "my_user#mail.com", "password" =>"my_password"})
But I keep getting 500 Internal Server Error.
Whay am I doing wrong?

Error occurred while parsing request parameters JSON::ParserError - 795: unexpected token at

I am trying to write the API methods for user to sign up on spree app. It's working properly on my local machine but not on server. here is my code of user_decorator_controller.rb
def sign_up
#user = Spree::User.find_by_email(params[:user][:email])
if #user.present?
render "spree/api/users/user_exists", :status => 401 and return
end
#user = Spree::User.new(user_params)
if !#user.save
unauthorized
return
end
#user.generate_spree_api_key!
end
and sign_up.v1.rabl is
object #user
attributes :id, :spree_api_key, :email, :firstname, :lastname, :mobile
child(:bill_address => :bill_address) do
extends "spree/api/addresses/show"
end
child(:ship_address => :ship_address) do
extends "spree/api/addresses/show"
end
when I CURL the server with below request
curl -v -H 'Content-Type: application/json' -H 'Accept: application/json' -X POST -d {"user":{"email":"ml5698#gmail.com","password":"12345678", "firstname":"M", "lastname":"L", "mobile":"9999888877"}} http://localhost:3000/api/users/sign_up
It gives me above error below is extracts from web server log
Started POST "/api/users/sign_up" for 127.0.0.1 at 2015-10-15 11:23:36 +0530
ActiveRecord::SchemaMigration Load (0.3ms) SELECT `schema_migrations`.* FROM `schema_migrations`
Error occurred while parsing request parameters.
Contents:
{user:{email:ml5698#gmail.com,password:12345678,
JSON::ParserError - 795: unexpected token at '{user:{email:ml5698#gmail.com,password:12345678,':
json (1.8.3) lib/json/common.rb:155:in `parse'
activesupport (4.2.4) lib/active_support/json/decoding.rb:26:in `decode'
I am using Ruby 2.2 , rails 4, json 1.8.3 , what could be the issue, please help me resolve it.
Your error is actually in your use of your command line curl. You use the -d switch, and pass parameters to it. The parameters are only parsed until the next space, so your parameters being passed in are
{user:{email:ml5698#gmail.com,password:12345678,
This is what you're seeing in the error message, and is obviously not well formed JSON, so you get the parsing error.
Try quoting your -d parameters like so:
curl -v -H 'Content-Type: application/json' -H 'Accept: application/json' -X POST -d '{"user":{"email":"ml5698#gmail.com","password":"12345678","firstname":"M","lastname":"L","mobile":"9999888877"}}' http://localhost:3000/api/users/sign_up

How to insert into RAILS db via external RESTful call

SOLVED: I had done a few things wrong, all of which involved my controller RECEIVING the data. There was not anything wrong with the methods below on SENDING the data.
1: I was not using #report.save in my reportController#create
2: I was not passing params[:report] in my controller
3: I added "skip_before_filter :verify_authenticity_token" to my applicaiton controller to stop warnings in the logs.
Solved. data insertion successful.
=====ORIG. Question Below=====
I need an external program to issue a command that inserts stuff into a Ruby on Rails database.
I understand the security implications of this, but because this application is not public facing, it is not really an issue.
This is the workflow i am looking to achieve:
REST client > RAILS > create new DB TABLE row
For purposes of example: my route.rb file contains
resources :reports
so i am able to CRUD using those routes. I just cant seem to get my rest client to work correctly.
UPDATE:
I have tried a RUBY rest client AND curl command in ONE, to no avail.
require 'rest_client'
require 'json'
hash_to_send = {:test_name => 'Fake Name', :pass_fail => 'pass',:run_id => 1111, :category => 'Fake Category'}
#formulate CURL attempt
myCommand = "curl -H 'Content-Type: application/json' -X POST http://localhost:8889/report.json -d #{hash_to_send.to_json} > deleteme.html"
#execute CURL attempt
`#{myCommand}` # RESULT--> 795: unexpected token at 'test_name:Fake Name'
#Make Ruby rest client attempt
response = RestClient.post( "http://localhost:8889/report.json",
hash_to_send.to_json,
:content_type => :json, :accept => :json
)
#debug info
puts myCommand # Returns --> {"test_name":"Fake Name","pass_fail":"pass","run_id":1111,"category":"Fake Category"}
Instead of curl in command-line, use ruby script and handle REST calls and JSON conversion by gems. For example, using rest-client gem (https://github.com/archiloque/rest-client) and standard json gem you can write:
require 'rest_client'
require 'json'
response = RestClient.post( "http://localhost:8889/report.json",
params_in_hash.to_json,
{ :content_type => :json, :accept => :json }
)

Rails Status 406 POST response

I'm been struggling with this issue for the past 4 hours. Whenever I send in a POST request with no arguments (body="{}"), I get a response back with a 406 HTTP Status Error Code.
My controller looks as simple as
def resetFixture
respond_to do |format|
format.json { render :json=>final_obj, :status=>:ok}
end
end
Routes:
match 'TESTAPI/resetFixture' => 'users#resetFixture', :via => :post
I'm trying to return a JSON response with "{errCode:1}"
If I do a curl request with -d "" , I get the response I want, but how do I fix this error code? I appeared to have already specified JSON and the status.
It might be more intuitive if I also included the debug logs from the server for the failing request:
Since you can't request resetFixture.json then you'll need to add the following header to your request:
Accept: application/json
This will tell rails that you want JSON back.
You can test this with curl by adding the following argument: -H "Accept: application/json"
Alternatively, if you want Rails to always default to JSON you can change your route to:
match 'TESTAPI/resetFixture' => 'users#resetFixture', :via => :post, :defaults => { :format => 'json' }

Resources