NoMethodError - undefined method for nil:NilClass: - ruby-on-rails

I am Rails noob and I am trying to unsderstand this simple JSON parsing code from a tutorial. Why do I get the nil:NilClass Error? What is a NilClass?
Thanks!
app.put '/users/update' do
params = JSON.parse(request.body.read)
reqUserID = params[:id]
requestUser = Models::Persistence::User.find_by_id(reqUserID)
content_type "application/json"
puts "Hello"
puts requestUser.username
if (requestUser)
status 401
return
end

Null, in Ruby is called nil and like everything else, nil is also an object. An object of NilClass.
You get this error if you try to call a method on a nil object.
So in this case, requestUser is probably nil

Related

Confirmation URL for Shopify RecurringApplicationCharge is nil

Im trying to add a recurring charge to my shopify app. I followed the Shopify-Tutorial but wrote it slightly different. My root route goes to:
root 'mycontroller#charging'
the controller action is:
def charging
if #shop_domain != #myshop
#shop_charging_status = #shop.charging
unless ShopifyAPI::RecurringApplicationCharge.current
recurring_charge = ShopifyAPI::RecurringApplicationCharge.new(
name: "My App",
price: "1.99",
return_url: "https:\/\/appurl\/activated",
trial_days: 7,
terms: "$1.99 per month")
if recurring_charge.save
#tokens[:confirmation_url] = recurring_charge.confirmation_url
#shop_charging_status = true
#shop.save
redirect recurring_charge.confirmation_url
end
end
else
redirect_to myindex_path
end
When I try to start the app, i get an error: NoMethodError (undefined method `[]=' for nil:NilClass). It concerns the #token line. This line already confused me when i wrote the code, because the variable #token is only used in this method. But nevertheless, why is it nil?
What am I missing?
When I try to start the app, i get an error: NoMethodError (undefined method `[]=' for nil:NilClass). It concerns the #token line.
I assume you mean #tokens?
I think you're missing the first part of the tutorial here in which they set #tokens = {} in the initialize method and then store the access tokens for each shop in there.

rails model returns nilClass although it contains data

I have a send method inside destinations_group_controller.
def send
#destinations_group = DestinationsGroup.all
puts #destination_group.class #prints NilClass
redirect_to destinations_groups_path
end
DestinationsGroup.all returns NilClass although the data exist. I checked in ruby console and it returns:
ActiveRecord::Relation [#< DestinationsGroup id: 1, title: ...>
any ideas why i cannot get this data from code?
Seems to be a typo (#destinations_group instead of #destination_group):
puts #destinations_group.class #prints NilClass

undefined method `[]' for nil:NilClass

def creation
(1..params[:book_detail][:no_of_copies].to_i).each do |i|
logger.info "nnnnnnnnnnn#{i}"
#book_details= BookDetail.new(params[:book_detail])
#book_details.save
end
And the Error is
undefined method []' for nil:NilClass
app/controllers/book_details_controller.rb:16:increation'
Is anybody can tell what is the problem?
Error you are getting is because params[:book_detail] is nil and you are calling [:no_of_copies] on it i.e. nil.So it is giving following error
undefined method []' for nil:NilClass
So you need to check first if params[:book_detail] is present or not like following
(1..params[:book_detail][:no_of_copies].to_i).each do |i|
logger.info "nnnnnnnnnnn#{i}"
#book_details= BookDetail.new(params[:book_detail])
#book_details.save
end if params[:book_detail] && params[:book_detail][:no_of_copies]
In addition is Salil's answer, you can use fetch
params.fetch(:book_detail, {})[:no_of_copies]
which will return nil if params[:book_detail] is nil. (1..0).to_a returns an empty array so you can rewrite your code using the following
copies = (params.fetch(:book_detail, {})[:no_of_copies] || 0).to_i
(1..copies).each do |i|
logger.info "nnnnnnnnnnn#{i}"
#book_details= BookDetail.new(params[:book_detail])
#book_details.save
end

Getting HTTP response in Rails

In my Rails controller, I have the url that the user inputs:
url_parsed = URI.parse(url)
response = Net::HTTP.get_response(url_parsed)
If the user inputs www.google.com, it gives
undefined method `request_uri' for #<URI::Generic:0x00000002e07908 URL:www.google.com>
on the line response = ....
I want it to display my error page, instead of this error. How can I do it?
Don't know if your question is why it isn't working, or how to use the error message in the view.
Why you get the error
EDIT:
I think that it's because there is no protocol in 'www.google.com', 'http://www.google.com' should work
How to show the error
Rescue the error:
error = nil
begin
url_parsed = URI.parse(url)
response = Net::HTTP.get_response(url_parsed)
rescue => error
end
if error
#error_message = "Your URL wasn't good enough"
# or you can use error.message if you want
# then use #error_message in your view
else
# do stuff when ok
end

Simple Mongoid Validation for create! - how to display error messages

I'm using Rails 3 with mongoid 2 and have a simple question regarding mongoid validation.
if #forum.topics.create!(name: params[:topic][:name])
# success, do something
else
#should handle errors but doesn't
render 'new'
end
If I use the .create! method, it runs validations on a mongoid model class correctly, but it is not getting to the else block to display the error. Instead it returns a rails error page saying...
Mongoid::Errors::Validations in TopicsController#create
Validation failed - Name can't be blank.
That's good, but how do I display that in a view instead of getting an ugly rails error message page?
Try this way:
new_topic = #forum.topics.new(name: params[:topic][:name])
if new_topic.save
# success, do something
else
render 'new', errors: new_topic.errors.full_messages
end
with this way you will have the local variable errors which is a Hash formated like following:
new_topic.errors.full_messages # => ["\"Name\" can't be blank"]
you can rescue the Mongoid::Errors::Validations and use it's instance method to get the errors
new_topic = #forum.topics.new(name: params[:topic][:name])
new_topic.create!
rescue Mongoid::Errors::Validations => e
summary = e.summary
problem = e.problem
res = e.resolution
using the above error messages you can display the error
Documentaion link
https://docs.mongodb.com/mongoid/6.2/api/Mongoid/Errors/Validations.html

Resources