I want to add data to table through rest api with url: localhost:3000/api/v1/shoppinglists#create?grocery=fruits
I have created a model already, my controller is located under api/v1/shoppinglists_controller.rb and the code for that is:
shoppinglists_controller.rb:
module Api
module V1
class ShoppinglistsController < ApplicationController
def index
shop = Shoppinglist.all
render json: shop.to_json
end
def create
#tst = Shoppinglist.create(grocery: params[:grocery])
end
end
end
end
routes.rb:
Rails.application.routes.draw do
namespace :api do
namespace :v1 do
get '/shoppinglists' => 'shoppinglists#index'
post '/shoppinglists' => 'shoppinglists#create'
end
end
end
Model-migration: shoppinglist.rb:
class CreateShoppinglists < ActiveRecord::Migration
def change
create_table :shoppinglists do |t|
t.integer :shopid
t.string :type
t.string :grocery
t.string :status
t.timestamps null: false
end
end
end
By default, def index gets triggered but when I do: localhost:3000/api/v1/shoppinglist#create?grocery=fruits then I check on commandline, I still see:
Started GET "/api/v1/shoppinglists" for ::1 at 2015-06-23 23:59:06 -0400
Processing by Api::V1::ShoppinglistsController#index as HTML
Shoppinglist Load (0.3ms) SELECT "shoppinglists".* FROM "shoppinglists"
Completed 200 OK in 44ms (Views: 0.2ms | ActiveRecord: 0.4ms)
and my table is empty. There are 2 problems:
I dont understand why still index is getting triggered and how can I make def create to actually insert value in grocery column through rest api.
[Solved] I used a client called Postman to solve this problem but still facing problem (2) as all null values are entered in my table and not the one being entered through url. My command line logs now say [logs]
Once it gets triggered then is my code right for "create" def?
[Solved] Issue was with the way I was sending values through post. I had to add values to form-data tab (key,val) in Postman instead of through url for it to work
[logs]
Started POST "/api/v1/shoppinglists" for ::1 at 2015-06-24 01:03:44 -0400
Processing by Api::V1::ShoppinglistsController#create as */*
Can't verify CSRF token authenticity
(0.2ms) begin transaction
SQL (0.3ms) INSERT INTO "shoppinglists" ("created_at", "updated_at") VALUES (?, ?) [["created_at", "2015-06-24 05:03:44.714945"], ["updated_at", "2015-06-24 05:03:44.714945"]]
(8.2ms) commit transaction
Completed 200 OK in 12ms (ActiveRecord: 8.7ms)
Create action requires a POST request and when you visit localhost:3000/api/v1/shoppinglist#create?grocery=fruits in a browser, it sends a GET request instead of a POST request, treating it as a URI and hence triggering index action. To send a POST request you can use CURL command in terminal or httparty
curl -H 'Content-Type: application/json'-H 'Accept: application/json' -X POST http://localhost:3000/api/v1/shoppinglists -d {"grocery": "fruits"}
where -H refers to the headers set in request and -X is for changing default GET verb and -d is for the data that you want to send. For details refer to curl
Related
I'm having a problem where I've successfully registered a resource in ActiveAdmin, but I can't create or update any records. I think it's due to a namespacing issue. Can I override it using an option while registering the resource?
I'm building a Rails Engine that registers AA resources from within the engine. I followed the instructions here.
My engine contains lib/admin/myengine/myresources.rb
if defined?(ActiveAdmin)
ActiveAdmin.register Myengine::Myresource do
end
end
In the test/dummy app, the relevant schema looks like:
create_table "myengine_myresources", force: :cascade do |t|
t.string "name"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
When I run the dummy app server, I successfully navigate to http://localhost:3000/admin/myengine_myresources and click 'New Myengine Myresource'
I type in a name and click 'Create Myresource', but it treats the request as if I've submitted blank attribute values.
The server log shows:
Started POST "/admin/myengine_myresources" for ::1 at 2015-12-02 11:13:52 -0800
Processing by Admin::MyengineMyresourcesController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"stuff", "myresource"=>{"name"=>"Arbitrary Name"}, "commit"=>"Create Myresource"}
(0.1ms) begin transaction
(0.1ms) rollback transaction
Rendered /Users/me/.rvm/gems/ruby-2.2.3/gems/activeadmin-1.0.0.pre2/app/views/active_admin/resource/new.html.arb (190.7ms)
Completed 200 OK in 231ms (Views: 199.4ms | ActiveRecord: 0.2ms)
My working theory is that the params need to be inside :myengine_myresource rather than just :myresource.
Any ideas on how to get that working?
Here's one workaround:
if defined?(ActiveAdmin)
ActiveAdmin.register Myengine::Myeresource do
controller do
def permitted_params
params[:myengine_myresource] = params.delete :myresource
params.permit(myengine_myresource: [:my, :list, :of, :accepted, :params])
end
end
end
end
I want to get information from the TwitchTV OAuth API, and the authorization works well, but I can not get the code that Twitch redirects me to.
For example:
http://localhost/?code=noj4n39487fn29fn23v92hr293hnru23v97hre&scope=
This is how Twitch redirects back to my page. In the log of my rails server it also shows the following:
Started GET "/?code=q5yptiyx3cdaep52b7xyqgt3vjpwhg&scope=" for 371.1721.13.179 at 2015-08-22 17:09:26 +0200
Cannot render console from 315.127.134.179! Allowed networks: 127.0.0.1, ::1, 127.0.0.0/127.255.255.255
Processing by HomeController#index as HTML
Parameters: {"code"=>"q5ypti345ferf2rf2efr2erferfe23ff", "scope"=>""}
News Load (0.6ms) SELECT "news".* FROM "news"
Rendered home/index.html.erb within layouts/home (14.7ms)
Completed 200 OK in 124ms (Views: 120.6ms | ActiveRecord: 1.0ms)
But when I try to get params.inspect in the controller, it shows this:
{"controller"=>"oauth", "action"=>"index"}
my controller looks like this:
class OauthController < ApplicationController
def index
redirect_to 'https://api.twitch.tv/kraken/oauth2/authorize?response_type=code&client_id=34n87fn48fn438rzfghb4z8rofg4rg&redirect_uri=http://localhost/'
logger.info params.inspect
end
end
Obviously I changed all the ip's, auth-codes and stuff. My question is, shouldn't params return the parameters since it shows them as parameters (in the first code block) ?
Localhost is local address and 'outworld' API cannot send information back to 'localhost', you have to use http://127.0.0.1 or get a real domain for you development environment.
I am making an ajax post call to a controller. My Ajax call is:
$.ajax({
type:'POST',
url:'/chefUI/configure/save_roles',
data:{ app_name: appname, role_list: role_list},...});
My Routes file is:
scope "/chefUI" do
post '/configure/save_roles', to: 'admin#update_app_roles'
end
And my controller has:
def update_app_roles
begin
application_name = params["app_name"]
puts application_name
role_name_list = params["role_list"]
puts role_name_list
if application_name and !role_name_list.empty?
...
And I am getting a 405 Method Not Allowed response. I'm not sure what are the reasons this might happen. Could someone help me figure out what I'm missing here? I don't why my post request is not even reaching my controller.
Update:
Log file
Started GET "/chefUI/configure/app_roles?app_name=MFRH" for 127.0.0.1 at 2015-07-24 15:08:51 +0530 Processing by AdminController#app_roles as */* Parameters: {"app_name"=>"MFRH"} [1m[35mUser Load (1.0ms)[0m SELECT "users".* FROM "users" WHERE "users"."username" = $1 LIMIT 1 [["username", "an9v0s7"]] [1m[36mApplication Load (2.0ms)[0m [1mSELECT "applications".* FROM "applications" WHERE (lower(app_name) = 'mfrh') ORDER BY "applications"."id" ASC LIMIT 1[0m [1m[35mRole Load (1.0ms)[0m SELECT "roles".* FROM "roles" INNER JOIN "application_roles" ON "roles"."id" = "application_roles"."role_id" WHERE "application_roles"."application_id" = $1 ORDER BY roles.name ASC [["application_id", 1]] Completed 200 OK in 217ms (Views: 0.0ms | ActiveRecord: 5.0ms)
Started POST "/chefUI/configure/save_roles" for 127.0.0.1 at 2015-07-24 15:08:57 +0530
Another Update:
I just found out that I'm getting that response for all my post requests. They were all working before, I created a bunch on new models and suddenly none of them are working.
This problem is a bit deeper than thought before.
Rails does not like when a route path and the asset directory are in the same subdirectory.
When making a post request, you will get method not allowed. The problem is there can be no overlap with paths and the asset directory. The problem is specifically with POST requests in that path. I am assuming somewhere in rails, they must have disabled all non-GET requests for the assets directory.
scope "/chefUI" do
post '/configure/save_roles', to: 'admin#update_app_roles'
end
config.assets.prefix="/chefUI/assets"
^ You need this part so they don't overlap.
In this very simple app below, you will get a method not allowed error. Because the path /welcome is being used for a route and for an asset prefix.
File: config/environment/development.rb
config.assets.prefix = '/welcome'
File: config/routes.rb
resources :welcomes, path: 'welcomes', only: ['index', 'create']
File: app/controllers/welcomes_controller.rb
class WelcomesController < ApplicationController
def index
#welcome = 'hello';
end
def create
#welcome = 'world';
end
end
File: app/views/welcomes/index.html.rb
<%= form_for(#welcome) do |f| %>
<%= f.submit 'Submit' %>
<% end %>
File: app/views/welcomes/create.html.rb
<h1>Welcomes#create</h1>
<p>Find me in app/views/welcomes/create.html.erb</p>
I removed the below line in application.rb and the issue got resolved. config.assets.prefix="/chefUI"
I don't understand what config.assets.prefix has to do with POST requests, but this resolved my issue.
Would love to understand the reason though.
For some reason both these URLS are routing to the same file when they shouldn't be, another thing that I noticed when typing in an invalid url such as localhost:3000/topics/inexjojvnsjg it just stays on the same page.
here is what my rails console is telling me when I try to access the url
localhost:3000/topics/index
Started GET "/topics/index" for ::1 at 2015-02-06 17:33:07 -0700
Processing by TopicsController#show as HTML
Parameters: {"id"=>"index"}
Rendered topics/show.html.erb within layouts/application (0.1ms)
User Load (0.8ms) SELECT "users".* FROM "users" WHERE "users"."id" =$1 ORDER BY "users"."id" ASC LIMIT 1 [["id", 1]]
Completed 200 OK in 98ms (Views: 96.5ms | ActiveRecord: 0.8ms)
here is my routes file....
Rails.application.routes.draw do
devise_for :users
get 'welcome/index'
get 'welcome/about'
# get "topics/index"
# get "topics/show"
# get "topics/new"
# get "topics/edit"
#for some reason, using resources:topics, index and show both route to show
resources :topics
root to: 'welcome#index'
post :incoming, to: 'incoming#create'
end
Here is the key info:
Started GET "/topics/index" for ::1 at 2015-02-06 17:33:07 -0700
Processing by TopicsController#show as HTML
Parameters: {"id"=>"index"}
The :index url for a TopicsController is "/topics".
The :show url for a TopicsController is "/topics/:id" or "/topics/1", where the last part of the url gets associated to the params[:id]. With the url "/topics/1" the :id = 1.
So when you go to the url "/topics/index" you are going to the :show action because of the "index" part of the url. You are just setting the :id to "index" instead of a Integer :id. You can see that in the output you pasted here:
Parameters: {"id"=>"index"}
TLDR: "/topics/index" is a route the will pass the Rails router but is an invalid route, because the :id is a String "index".
I have a bunch of logger.debug statements in my Controller. They currently write the place where all the HTTP requests and everything are displayed in real time on my WEBRick server. However,
when I write logger.debug statements in my Model, they are not written to this same location, additionally they are not to be found in log/development which is the environment I have been working in. It is particularly frustrating because I make the call to the following Model function in a controller that has successfully executed logger.debug statements:
def process_payment
uri = URI('https://demo.myvirtualmerchant.com/VirtualMerchant/processxml.do')
the_xml = SchoolApplication.to_xml(params[:credit_card],
params[:expiration],
params[:cvv2_cvc2],
params[:amount],
params[:name])
logger.debug(the_xml)
the_xml = the_xml.to_s
my_hash = {'xmldata' => the_xml}
logger.debug(the_xml)
response = Net::HTTP.post_form(uri, my_hash)
#response_var = response
if response.response == 0
render 'receipt'
else
render 'card_Error'
end
end
the two logger.debug statements in this controller method are written to what I suppose is STDOUT? In any case I see them in the location which displays the following kind of information:
Rendered web_applications/card_Error.html.erb within layouts/application (1.7ms)
Completed 200 OK in 433ms (Views: 13.1ms | ActiveRecord: 0.0ms)
Started GET "/assets/jquery.js?body=1" for 127.0.0.1 at 2014-07-22 11:32:02 -0700
In the above Controller method when I make the call to SchoolApplication.to_xml,
it does not execute the corresponding logger.debug() statements (or maybe it writes them
to a different place? That wouldn't make sense but I am also a n00b, clearly) that are in
to_xml Model method as shown below:
def self.to_xml(number,expiration,cvv,amount, name)
xml = ::Builder::XmlMarkup.new
logger.debug(number)
logger.debug(name)
xml.txn {
xml.ssl_test_mode false
xml.ssl_card_number number
xml.ssl_amount amount
xml.ssl_cvv2cvc2_indicator cvv
xml.ssl_first_name name
xml.ssl_show_form false
xml.ssl_exp_date '25/34'
xml.ssl_track_data
xml.ssl_result_format HTML
xml.ssl_receipt_link_method
xml.ssl_receipt_link_url "#{Rails.root}" + '/receipts/receive'
xml.ssl_receipt_link_text
}
xml
end
N.B. I know that the above to_xml is being successfully called and returned from as the rest of my controller method which calls this model function executes without error.
Here is the output after I go to the route which calls the process_payment controller function:
Started POST "/application/pay" for 127.0.0.1 at 2014-07-22 12:13:40 -0700
Processing by WebApplicationsController#process_payment as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"pJD6Q7qJPXFNaGEczv5kTSKBC5TcG8lqhOuLNjw9UrY=", "web_application"=>{"first_name"=>"bob", "last_name"=>"job", "card_number"=>"41111111111111", "expiration_date"=>"232", "cvv2_cvc2"=>"232"}, "commit"=>"Save Web application"}
<txn><ssl_merchant_id/><ssl_user_id/><ssl_ssl_pin/><ssl_test_mode>false</ssl_test_mode> <ssl_card_number/><ssl_amount/><ssl_cvv2cvc2_indicator/><ssl_first_name/ ><ssl_show_form>false</ssl_show_form><ssl_exp_date>25/34</ssl_exp_date><ssl_track_data/><ssl_result_format>HTML</ssl_result_format><ssl_receipt_link_method/><ssl_receipt_link_url> <ssl_receipt_link_text/></txn><to_s/>
<txn><ssl_merchant_id/><ssl_user_id/><ssl_ssl_pin/><ssl_test_mode>false</ssl_test_mode> <ssl_card_number/><ssl_amount/><ssl_cvv2cvc2_indicator/><ssl_first_name/><ssl_show_form>false</ssl_show_form><ssl_exp_date>25/34</ssl_exp_date><ssl_track_data/><ssl_result_format>HTML</ssl_result_format><ssl_receipt_link_method/>
Rendered web_applications/card_Error.html.erb within layouts/application (3.8ms)
Completed 200 OK in 742ms (Views: 22.6ms | ActiveRecord: 0.0ms)
which is equivalent to what was written in development.log