Ruby on rails: undefined method `[]' for nil:NilClass? - ruby-on-rails

when i try to create it says undefined method.
def create
#stock = Stock.find(params[:stock_availabilities][:stock_id])
#stock_availability = StockAvailability.new(stock_availabilities_params)
respond_to do |format|
if #stock_availability.save
format.html { redirect_to stock_path(v_id: #volunteer.id), notice: "stock saved successfully" }
else
#stock_availabilities = StockAvailability.where(stock_id: #stock.id).all
format.html { render 'index' }
end
end
end
Where stock_availabilities belongs to Stock table. foreign key is stock_id.
The params Generated in log is
Parameters: {
"utf8"=>"✓",
"authenticity_token"=>"ZWxRnGJqwLmhfosIhQ+xdLrG3HJXy1m/dHcizT+Y5+E=",
"stockavailability"=>{
"qty"=>"20",
"price"=>"2000",
"captured_at"=>"26/8/2015"
},
"commit"=>"Save Stockavailability"
}
Completed 404 Not Found in 1ms

I kind of regenerated your issue
2.1.1 :003 > a=nil
=> nil
2.1.1 :004 > a['asd']
NoMethodError: undefined method `[]' for nil:NilClass
from (irb):4
from /home/illu/.rvm/rubies/ruby-2.1.1/bin/irb:11:in `<main>'
2.1.1 :005 >
In your case it probably
params[:stock_availabilities] is giving nil and you are trying to access the key :stock_id in the nil class.
I suggest you to pry the values at the point.
EDIT1:
After having a look at your server log it is clear that the key stock_availabilities you are trying to access is actually stockavailability
your code should be like
# though no :stock_id key/value is found in your server log
#stock = Stock.find(params[:stockavailability][:stock_id])

try change :
#stock = Stock.find(params[:stock_availabilities][:stock_id])
to
#stock = Stock.find(params[:stockavailability][:stock_id])
Your this problem will get solved but you will get other error too. Because you are not passing stock_id properly in params. So try set that as well in form hidden field.
To run your code without error. You should have stock_id in your this param section "stockavailability"=>{"qty"=>"20", "price"=>"2000", "captured_at"=>"26/8/2015"},

Related

Rails 5 testing controller unfiltered params

I have recently upgraded my application to Rails 5 and when I am testing my controller I am getting the following error:
ActionController::UnfilteredParameters: unable to convert unpermitted parameters to hash.
My controller code looks like this:
def bid
widget_mode = params.include?(:widget)
if !#auction.published?
redirect_to '/' #go to the homepage
elsif #auction.third_party?
redirect_to #auction.third_party_bidding_url
elsif current_user && current_user.clerk? &&
!#auction.listing? &&
(#auction.items_count == 1 || params["section"] == "auction") &&
!widget_mode
redirect_to action: 'clerk', id: #auction.id, params: params.slice(:item, :section)
else
# Make sure the auction is in firebase
exists = #auction.rt_get('updated_at').body.to_i > 0 rescue false
#auction.queue_realtime_update unless exists
end
end
and my test code looks like this:
test "should redirect to powerclerk if multi item auction and params section = auction" do
sign_in users(:clerk)
a = auctions(:kenwood_dr)
assert a.items.count > 1, "Expected auction to have more than one item"
get :bid, params: {id: a.id, item: a.items.first.id, section: "auction"}
assert_redirected_to "/clerk/1?item=1&section=auction"
end
I tried adding:
params.permit(:item, :section, :id, :controller, :action, :widget)
to the beginning of my bid controller method and that didn't make a difference. Any insight would be appreciated.
This error occurs when calling to_h or to_hash on an instance of ActionController::Parameters that doesn't have any permitted keys (documentation).
Since ActionController::Parameters#slice returns an instance of the same, this code does not give you a hash like it would seem: params.slice(:item, :section).
In most cases you can use permit instead of slice on parameters instances. If you ever want to bypass the safe access whitelisting of ActionController::Parameters you can use permit! and use ActionController::Parameters#slice, or if you want to convert to a hash without sanitization you can use to_unsafe_h.
I ended up solving this by switching:
redirect_to action: 'clerk', id: #auction.id, params: params.slice(:item, :section)
to
redirect_to action: 'clerk', id: #auction.id, params: params.permit(:item, :section)

undefined method `+' for nil:NilClass spree

I am running a spree app.
I am getting below error when I try to add any product in the cart.
undefined method `+' for nil:NilClass
This error comes only when I add option types and variants of the same product.
I am not sure what's exactly going wrong here, because I am not doing any changes in the code or something.
This is the extracted source it shows.
if quantity.between?(1, 2_147_483_647)
begin
order.contents.add(variant, quantity, options)
rescue ActiveRecord::RecordInvalid => e
error = e.record.errors.full_messages.join(", ")
end
Here's my order controller's populate function.
# Adds a new item to the order (creating a new order if none already exists)
def populate
order = current_order(create_order_if_necessary: true)
variant = Spree::Variant.find(params[:variant_id])
quantity = params[:quantity].to_i
options = params[:options] || {}
# 2,147,483,647 is crazy. See issue #2695.
if quantity.between?(1, 2_147_483_647)
begin
order.contents.add(variant, quantity, options)
rescue ActiveRecord::RecordInvalid => e
error = e.record.errors.full_messages.join(", ")
end
else
error = Spree.t(:please_enter_reasonable_quantity)
end
if error
flash[:error] = error
redirect_back_or_default(spree.root_path)
else
respond_with(order) do |format|
format.html { redirect_to cart_path }
end
end
end
Please help me out here.
You need to ensure the values of variant, quantity and options before sending them to spree.
The fact that you get this error could be considered as a bug on their side, since you'd expect a nice error message saying "variant is nil" or the like.
To fix your problem though, I'd check that these values are valid ones before sending them to spree.
For future views about this issue.
Check if the Variant cost_currency attribute is the same that is configured in Spree. You can check it in a rails console doing:
Spree::Config.get(:currency)
Sometimes it happens when spree is initialized with some currency by default and then the default currency is changed.

How can I circumvent a raised exception (even when using find_by_id)

As the title suggests - an exception was being raised in production on Heroku, even when I use find_by_id. I'm not sure what the cause is, but I have used a begin/ensure to circumvent the issue, but I am still running into an issue.
here was my initial solution:
def select_location
begin
region = Region.find_by_id(params[:Digits])
ensure
Twilio::TwiML::Response.new do |r|
# if user pressed "9" (redirect)
if (params[:Digits] == '0')
#response = r.Redirect call_hq_path, method: 'GET'
# if region does not exist
elsif !region.id
#response = r.Play Clip.where(name: "invalid").first.url
#response = r.Redirect index_path, method: 'GET'
else
#response = r.Gather action: location_description_path(region), numDigits: '1' do |g|
region.locations.order(:number).each do |location|
g.Play location.listing_clip.url
g.Play number_url(location.number)
end
g.Play Clip.where(name: "9toreturn").first.url
end
end
end
end
render :xml => #response
end
The problem here lies at elsif !region.id - am still running into this error:
2013-10-18T01:29:14.524289+00:00 app[web.1]: NoMethodError (undefined method `id' for nil:NilClass):
So, my two questions:
is begin/ensure the best way to circumvent the issue?
if yes, how do I fix the elsif problem?
update
After removing .id from the elsif - I get this error:
2013-10-18T02:06:57.055617+00:00 app[web.1]: NoMethodError (undefined method `url' for nil:NilClass):
How is the elsif not firing?
elsif !region.id does not check if region exists, it checks if id property of the region object returns nil. If region doesn't exist (and hence is nil), you're effectively calling nil.id, which is what is raising the exception.
If you just want to check if region is nil, elsif !region should suffice.
(From what you have here, it also doesn't really look like there's any need for the begin/ensure block either.)

Rails Parse Active record validation error

I have the following in my controller:
def create
equipment = Equipment.create(:name => params[:name])
errors = equipment.errors.messages
puts "equipment errors: " + errors.inspect
respond_to do |format|
format.json { render :json => #equipment }
end
end
The response from the 'puts' is:
equipment errors: {:name=>["has already been taken"]}
How do I parse the error and get the message?
Thanks
equipment.errors.full_messages.join(", ")
This should give you "Name has already been taken". It concatenates all the errors.
Its just a hash. Access the message with
errors[:name].first
This gets the value of the :name key from the hash, which is an array with one element, and then returns the value of the first element of the array, which is the error message.
With more errors, use Array functions to access all of them and display them appropriately.

undefined method `coordinates' for nil:NilClass

I'm new to Rails and trying to figure out an issue with a Rails 2.3.14 site. The problem is this store locator i'm trying to fix keeps returning
undefined method `coordinates' for nil:NilClass
when it can't find a store within the distance parameters. If it finds one then it works ok.
Here is the current code i'm trying to work with in my controller
#map = GMap.new("locations-gmap-div", "locationsGMap")
#map.control_init(:large_map => true, :map_type => true)
#mapp.center_zoom_init(#locations.first.coordinates, 8)
This is what I tried to do with my code. I'm still very new to Rails so I apologize if i'm going way off field here.
#map = GMap.new("locations-gmap-div", "locationsGMap")
#map.control_init(:large_map => true, :map_type => true)
if #map.center_zoom_init(#locations.first.coordinates,8).nil?
flash[:error] = 'Sorry, we could not find any stores matching that criteria.'
redirect_to store_locator_path
else
#map.center_zoom_init(#locations.first.coordinates,8)
end
Any help would be greatly appriciated.
Its failing because the #locations are empty.
#locations will return []
#locations.first will return nil
nil.coordinates raises undefined method `coordinates' for nil:NilClass
if #locations.empty?
flash[:error] = 'Sorry, we could not find any stores matching that criteria.'
redirect_to store_locator_path
else
#map = GMap.new("locations-gmap-div", "locationsGMap")
#map.control_init(:large_map => true, :map_type => true)
#map.center_zoom_init(#locations.first.coordinates,8)
end
You haven't initialized #locations.first. The program seems to be trying to access the coordinates of something that doesn't exist (hence why the exception is on nil:NilClass).

Resources