undefined method `coordinates' for nil:NilClass - ruby-on-rails

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).

Related

undefined method `+' for nil:NilClass - Values are not null

I am trying to create a method that loops through some objects and if a certain attribute is true, adds to the cost of the lesson to the money received, but keep getting the error undefined method `+' for nil:NilClass.
Here is the piece of code (the line producing the error start #activity.update_attribute):
def show
#activity = Activity.find(params[:id])
#participants = Participant.all.where(:activity_id => #activity.id).map(&:user_id).uniq
#all_participants = Participant.all.where(:activity_id => #activity.id)
#all_participants.each do |a_participant|
if a_participant.paid
#activity.update_attribute(:money_received, #activity.money_received + #activity.cost)
end
end
#users = Array.new
#participants.each do |participant|
#users.push(User.find(participant))
end
end
And here is a screenshot from my database to show that neither is a null value:
Here is the error message that I get when running the application:
Any help would be greatly appreciated
Many thanks

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.

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

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"},

Facing issue NoMethodError (undefined method `include' for "56":String):

I am facing issue while writing this code
def sim_state
sim_employees = SimEmployee.find(params[:id].include(:employees))
respond_to do |format|
format.js {
render :layout => false,
:locals => {
:sim_employees => sim_employee
}
}
end
end
and in my sim_states.js.erb
$('#simState').text('<%= sim_employee.employees.app_state%>');
So it gives me this error
NoMethodError (undefined method `include' for "56":String):
when i use it with includes then it gives
undefined method `includes'
Please guide me how to solve this.
The reason is simple
params[:id]
is return you a String value which is "56" and includes works with ActiveRecord::Relation and not string. So you are not able to fire the query that ways.
SimEmployee.find(params[:id])
This will return again a result and not relation. Try using
SimEmployee.where(id: params[:id]).includes(:employees).first
This should help you.
PS : Using includes for one record is same as firing two independent queries i.e.
#sim_employee = SimEmployee.find(params[:id])
#emplyess = #sim_employee.employees
There is a simple solution for this:
SimEmployee.includes(:employees).find params[:id]
SimEmployee.find(params[:id].include(:employees))
This line is causing the issue, you are calling include(:employees) on params[:id] which would be a number.
And you can't actually do .find(params[:id].include(:employees) because find method returns an instance of Model class, in this case, an instance of SimEmployee class, and you can't run method include on it.
Edit:
SimEmployee.includes(:employees).where()
You can pass a hash in where(). This works if your SimEmployee model has has_many relation to Employee model.

Rails 4 custom json errors

I am using Rails 4 i am trying to set an api and i have a services controller where i def some methods like this:
def articles_stores
#article = Store.find(params[:id])
if #article.nil?
render :json => {:error_msg => "Record not found",:error_code => 404,:success => false}
else
render json: {article: #article.as_json({except: [:updated_at,:created_at]}),success: true}
end
end
But for some reason it is not rendering the error the else part works fine y also have all the necessary routes
Any help will be appreciated
#article.nil? will never be true if the article does not exist: Store.find(params[:id]) will already raise an exception if the record does not exist, and this than gets handled by rails automatically as a 404. If you want to return nil, use something like this:
Store.where(id: 10).first
# old, deprecated way:
Store.find_by_id(10)
Also see here.

Resources