I do have 2 table user and items. when I try to create an item through postman API. I get an error that items is nil cause it's looking for current_user.items and cause a user not coming from the API when I try to create an item.
@item = current_user.items.build(item_params)
the question of how to authenticate and become current_user when I try to create an item from postman?
here is the API I'm sending
http://localhost:3000/api/v1/createitem
and here is the error message
"exception": "#<NoMethodError: undefined method `items' for nil:NilClass>",
this items_controller.rb
class Api::V1::ItemsController < ApplicationController
def createitem
@item = current_user.items.build(item_params)
if @item.save
redirect_to listing_item_path(@item), notice: "Saved..."
else
flash[:alert] = "Something went wrong..."
render :new
end
end
def item_params
params.require(:item).permit(:item_category, :item_condition,:item_name,:summary,:address,:price,:active, :instant)
end
end
the error is happening on line 81 of the items_controller.rb which this line
@item = current_user.items.build(item_params)
this is the json in sending
{"item_category": "Books & Magazines", "item_condition": "Used", "item_name": "Crushing it", "summary": "super awesome", "price": 20, "active": true,"instant": 1}
here is application_controller.rb
class ApplicationController < ActionController::API
include Authenticate
rescue_from ActiveRecord::RecordNotFound, with: :render_404
def render_404
render json: { error: "Invalid ID", is_success: false}, status: 404
end
end
I do have an API for login which is this and it's working
http://localhost:3000/api/v1/login
First of all you have to define / fetch current_user
. as API is totally different than web application, they can't handle session as no browser involve. So we need to handle authorisation differently.
I assume your login API return some unique token for logged in user if not than you have to implement that first.
You have to pass that token in each API call in header and validate that token to fetch current_user
.
Please Read this for more reference.