Inject a shopify page through shopify-api in Rails - ruby-on-rails

Im trying to inject a new page to a shopify-store through the shopify-api which is included in the shopify-app gem. I added the authentication from the gem to my controller, which works perfect for GET-requests. Somehow the POST-Method does not work.
The method inject_page_method shall be called in my create method, which would then represent a second POST request.
Im confused, because the GET-methods already work. So I thought, the gem routes this endpoints for me like this:
def inject_page_method
#create_new_page = ShopifyAPI::Page.new(:title => "test", :body_html =>"<h1>Test</h1>")
#create_new_page.save
end
helper_method :inject_page_method
Finding out this does not work I tried it with a full endpoint request:
def create_new_page
page_data = {
"page": {
"title": "Test",
"body_html": "<h1>Test succeded</h1>"
}
}
#json_request_url = #shop_domain + "/admin/api/2020-07/pages.json"
Rails.ajax({
type:"POST",
url:#json_request_url,
data:page_data
})
end
Heroku logs --tail shows me, that the method is POST, which is fine, but I get a status=500 with following errors:
NoMethodError (undefined method `+' for nil:NilClass):
app/controllers/my_controller.rb:101:in `create_new_page'
app/controllers/my_controller.rb:37:in `create'
When I change the concatenation of #json_request_url to:
#json_request_url = "#{#shop_domain}/admin/api/2020-07/pages.json"
I get a status 500:
NoMethodError (undefined method `ajax' for Rails:Module):
Which is impossible because both Jquery and Rails/ujs are required in the application.js
Edit: This is on rails 6
What is missing?

Related

Weird error when testing a Rails + AngularJS app with Rspec and PhantomJS

I have an app that lists tickets. It uses AngularJS. Here's the controller action:
def index
#tickets = apply_scopes(#tickets)
response.headers['x-total-count'] = #tickets.total_count
response.headers['x-per-page'] = Ticket.default_per_page
end
The Angular controller (Coffeescript):
$scope.fetch = ->
Ticket.query($scope.search).then (response) ->
$scope.tickets = response.data
$scope.totalCount = response.headers('x-total-count')
$scope.perPage = response.headers('x-per-page')
$scope.fetch()
I'm using angular-rails-resource to fetch the records. Everything works smoothly if I test by hand.
Here is the spec:
let(:user) { create :user }
scenario 'User lists tickets', js: true do
login_as user, scope: :user
ticket = create :ticket, user: user
visit root_path
click_on 'Support Requests'
expect(page).to have_content(ticket.subject)
end
When I run this spec, I just get the regular Rspec failure message because the condition was not met, but it should have:
expected to find text "ticket 000" in...
I figured it had something to do with concurrency and Capybara not waiting for Angular to fetch and display the records. Then I went ahead and added a sleep 2 right above the expectation just to test that. When I do it, I get a different error:
Capybara::Poltergeist::JavascriptError:
One or more errors were raised in the Javascript code on the page. If you don't care about these errors, you can ignore them by setting js_errors: false in your Poltergeist configuration (see documentation for details).
Possibly unhandled rejection: {"data":"<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\">\n<HTML>\n <HEAD><TITLE>Internal Server Error</TITLE></HEAD>\n <BODY>\n <H1>Internal Server Error</H1>\n undefined method `split' for 1:Fixnum\n <HR>\n <ADDRESS>\n WEBrick/1.3.1 (Ruby/2.3.3/2016-11-21) at\n 127.0.0.1:54674\n </ADDRESS>\n </BODY>\n</HTML>\n","status":500,"config":{"method":"GET","transformRequest":[null],"transformResponse":[null],"jsonpCallbackParam":"callback","url":"/tickets","params":{},"headers":{"Accept":"application/json","Content-Type":"application/json"},"data":{}},"statusText":"Internal Server Error "}
Possibly unhandled rejection: {"data":"<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\">\n<HTML>\n <HEAD><TITLE>Internal Server Error</TITLE></HEAD>\n <BODY>\n <H1>Internal Server Error</H1>\n undefined method `split' for 1:Fixnum\n <HR>\n <ADDRESS>\n WEBrick/1.3.1 (Ruby/2.3.3/2016-11-21) at\n 127.0.0.1:54674\n </ADDRESS>\n </BODY>\n</HTML>\n","status":500,"config":{"method":"GET","transformRequest":[null],"transformResponse":[null],"jsonpCallbackParam":"callback","url":"/tickets","params":{},"headers":{"Accept":"application/json","Content-Type":"application/json"},"data":{}},"statusText":"Internal Server Error "}
at http://127.0.0.1:54674/assets/application-713835b1641be632b29f7502c00a879e171bca5d6d06a5f264afcd819c123e76.js:14363
Here is my stack:
rails (5.0.2)
capybara (2.12.1)
poltergeist (1.13.0)
rspec-core (3.5.4)
phantomjs 2.1.1
Additional info:
If I output something right before ending the controller action, it gets outputted. The execution is going through the entire action;
If I console.log something right before fetching tickets, it's outputted as well. However, the Promise is not being resolved.
I found out the issue was with my pagination headers (x-total-count and x-per-page). Converting them to String does the trick. The weird part is that it was working OK in development, but not in test environment. So, if anyone has this issue in the future, the solution in my case was:
def index
#tickets = apply_scopes(#tickets)
response.headers['x-total-count'] = #tickets.total_count.to_s
response.headers['x-per-page'] = Ticket.default_per_page.to_s
end
Notice .to_s being called when assigning the headers.

Object appears as existing and not at the same time

I've got some very strange issue which I cannot debug.
This is my code:
def find_order_and_payment
#payment = Spree::Payment.find_by_identifier(params['session_id'])
Rails.logger.info "payment_id #{#payment.id}"
#order = #payment.order
end
And this is the output:
I, [2014-01-17T16:39:43.084827 #12342] INFO -- : payment_id 187
I, [2014-01-17T16:39:43.090718 #12332] INFO -- : Completed 500 Internal Server Error in 448ms
NoMethodError (undefined method `id' for nil:NilClass):
app/controllers/payu_status_controller.rb:36:in `find_order_and_payment'
Line 36 is the line with Rails.logger. I don't understand, why I get correct id, but same line returns undefined method id? If I'll call above code from console everything works as expected.

Devise password recoverable module via ajax

I building a javascript frontend (ember) to a rails api, and I'm using devise for user authentication.
All works well, but the password reccovery is giving me a hard time. I looked at the views/devise/password/edit.html.erb in devise and the properties seem to be password, new_password and password_reset_token.
I'm catching the password reset token from the url that is emailed, and constructed the following ajax call from it:
$.ajax({
url: '/users/password.json',
type: 'PUT',
data: {password: this.get('password'), password_confirmation: this.get('passwordconfirmation'), reset_password_token: this.get('content.reset_token')}
});
I can see the call gets accepted, but I'm getting a devise error that I can't understand. I think it has something to do with the resource that is passed back from the standard view, but I thought I covered that by the /user part in the ajax call.
All that I can find on the web is about login and change password, nothing about this bit.
The error I'm getting is:
Started PUT "/users/password.json" for 127.0.0.1 at 2013-05-29 09:01:36 +0200
Processing by Devise::PasswordsController#update as JSON
Parameters: {"password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]", "reset_password_token"=>"[FILTERED]"}
Completed 500 Internal Server Error in 1ms
NoMethodError - undefined method `[]' for nil:NilClass:
(gem) devise-2.1.2/lib/devise/models/recoverable.rb:125:in `reset_password_by_token'
(gem) devise-2.1.2/app/controllers/devise/passwords_controller.rb:30:in `update'
Thanks for your time.
Solution was to wrap the properties in the resource (user in my case):
$.ajax({
url: '/users/password.json',
type: 'PUT',
data: {'user[password]': this.get('password'), 'user[password_confirmation]': this.get('passwordconfirmation'), 'user[reset_password_token]': this.get('content.reset_token')}
});
my way:
$.ajax({url: '/users/password', type: 'PUT', data: { password: $password, password_confirmation: $password_confirmation, current_password: $current_password }});
You can try it if you didn't solve it......

NoMethodError users_url with devise (ajax)

I use devise 2.2.2 with rails 3.2.11
I use devise with ajax requests
I changed the following configuration in initializers/devise.rb
config.navigational_formats = [:json, :html]
config.http_authenticatable_on_xhr = false
when I submit an empty sign in request, I expect to get a json response with errors hash, but i get a 500 instead (see below for the trace) (it works fine with sign up request)
here are my routes (nothing special)
devise_for :users
the trace:
Started POST "/users/sign_in.json" for 127.0.0.1 at 2013-01-27 13:33:45 +0100
Processing by Devise::SessionsController#create as JSON
Parameters: {"user"=>{"email"=>"", "password"=>"[FILTERED]"}}
Completed 401 Unauthorized in 1ms
Processing by Devise::SessionsController#new as JSON
Parameters: {"user"=>{"email"=>"", "password"=>"[FILTERED]"}}
Completed 500 Internal Server Error in 40ms
NoMethodError (undefined method `users_url' for #<Devise::SessionsController:0x007fe88ddd9550>):
You are probably overriding after_sign_in_path_for and have a code path in there that returns nil.
This causes devise to fall back to its default behaviour and call users_url to get the path to redirect to.
Why do I think this? Because you are having the same error I had (and lost some hair over) and also this bug report contains the github usernames of many other people who have been humbled by this particular issue.

Problem with Rails 3 and AMF , rails3-amf, RocketAMF

im trying to get AMF to work with Rails3.
I have succesfully installed rails3-amf-0.1.0 gem and the RocketAMF-0.2.1 gem.
In my app there is a controller with the following code:
def getRandomCards
#incoming = params[0]
#cards = Cardvo.first
respond_with(#cards) do |format|
format.amf { render :amf => #cards.to_amf}
end
end
through a call from Actionscript i would like to return some data in amf format.
further more, as mentioned in the instructions for rails3-amf i did the following.
in my production.rb under config/environment i added the line
config.rails3amf.map_params :controller => 'CardvosController', :action => 'getRandomCards'
an my amf gateway got
config.rails3amf.gateway_path = "/gateway"
The problem is:
Any call from Actionscript / Flash raises the following
(taken from the log )
Started POST "/gateway" for 192.178.168.1 at Fri Nov 19 15:13:28 +0100 2010
Processing by CardvosController#getRandomCards as AMF
Parameters: {0=>100.0}
[1m[36mSQL (0.4ms)[0m [1mSHOW TABLES[0m
[1m[35mCardvo Load (0.2ms)[0m SELECT `cardvos`.* FROM `cardvos` LIMIT 1
Completed 200 OK in 13ms (Views: 0.9ms | ActiveRecord: 0.5ms)
NoMethodError (undefined method `constructed?' for #<RocketAMF::Envelope:0x39ba868>):
The Amf file is created but the method, which is in remoting.rb from RocketAMF could not be found.
I think the error is thrown at request_parser.rb from Rails3AMF asking for constructed?
# Wrap request and response
env['rack.input'].rewind
env['rails3amf.request'] = RocketAMF::Envelope.new.populate_from_stream(env['rack.input'].read)
env['rails3amf.response'] = RocketAMF::Envelope.new
# Pass up the chain to the request processor, or whatever is layered in between
result = #app.call(env)
# Calculate length and return response
if env['rails3amf.response'].constructed?
For me it seems it is looking at the wron class for the method.
Where
NoMethodError (undefined method `constructed?' for #RocketAMF::Envelope:0x39ba868):
the essential part is
RocketAMF::Envelope:0x39ba868
which should be
RocketAMF:ANOTHER_CLASS:Envelope:0x39ba868
Am i right and where the heck is the error ?
Any help would be appreciated!
chris

Resources