NoMethodError (undefined method `each' for nil:NilClass): - ruby-on-rails

class Api::SurveyAnswersController < ApplicationController
def create
# #survey_answer = SurveyAnswer.new(survey_answer_params)
survey_answers = []
survey_id = params[:survey_id]
params[:questions].each do |q|
answer = {survey_id: survey_id, option_ids: [], question_id: q[:id],
title: q[:answer]}
if q[:options].present?
selected_options = q[:answer].split(',')
selected_options.each do |selected_option|
q[:options].each do |option|
if option[:title]== selected_option
answer[:option_ids] << option[:id]
#<todo add break when in this condition
end
end
end
survey_answers << answer
end
end
puts survey_answers
# #survey_answers = SurveyAnswer.create(survey_answers)
if SurveyAnswer.create(survey_answers)
render json: survey_answers
end
end
end
I have a survey model which has some questions. Each question contains answers. When I try to hit post request through postman to insert answers, it gives 505 internal server error with message "undefined method each for nil:nilclass". Can anybody tell what the problem is?

You are trying to run the .each loop an empty object.
Make sure that both
params[:questions]
and
q[:options]
are not empty (not equal to nil).
NoMethodError sometimes sounds very unrepresentative, especially if you're just starting off with Ruby.
Try to browse Stackoverflow next time, because this has been answered here.

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

Error while iterating through params

I get an error when I try to iterate through params
When running code below:
def create_score
#quiz = Test.find_by(password: session[:test_password])
#points = 0
#quiz.tasks.each_with_index do |task, index|
#task = Task.find_by(id: task)
#points += #task.score if #task.correct_answers.to_s == send("params[:test][:task#{index}]")
end
#score = Score.new(user_id: 2, name: "Test1", points: #points)
if #score.save
redirect_to root_url
else
redirect_to signup_path
end
end
I get:
undefined method `params[:test][:task0]' ...
at the
#points += #task.score if #task.correct_answers.to_s == send("params[:test][:task#{index}]")
Which means that it has problem with send method
Parameters look like this:
{"utf8"=>"✓",
"authenticity_token"=>"8h7rtv2yWio11DFo6kBKutdZl7RDBBaTrt7e8qel8fR5R5XsoXRhRrBeDQPPoZeuBlZ7N5PmqCxik06Z/gQLZQ==",
"test"=>{"task0"=>["4"], "task1"=>["0"], "task2"=>["10"]},
"commit"=>"Zakończ test",
"locale"=>"pl"}
Which means that there is params[:test][:task0], but still for some reason it fires an error, but I don't really know why. Any ideas why this happens?
You want to index with dynamic key, not call a method dynamically. Aka:
params[:test]["task#{index}"]
Should do. Note that params are have indifferent access for strings and symbols.
To give you more food for thought, here is how you might have done the same with #send:
params[:test].send(:[], "task#{index}")
And here is how to define a method that would have the name you are trying to call:
define_method("params[:test][:task#{index}]") do
puts 'WTF'
end
You're calling your params with a symbol but instead you should use a string.
This means you should use one of the following approaches:
params["test"]["task0"]
or
params[:test.to_s][:task0.to_s]
Hope that helped :)
You should use params object something likeparams[:test][:task]) instead of send("params[:test][:task#{index}]".

rails method undefined job_apps

I get and error undefined method 'job_apps' (tried with single form 'job_app' too)
def accept
#job_apps = job_apps.find(params[:id])
#job_apps.update_attribute(status: :accept)
end
def refuse
#job_apps = job_apps.find(params[:id])
#job_apps.update_attribute(:status,2)
end
routes:
get 'accept' => 'job_apps#accept'
post 'accept' => 'job_apps#accept'
Tried:
def accept
#job_apps = #user.job_app
#job_apps.update_attribute(status: :accept)
end
I had similar trouble for calling the job_app in the same view (to see job_app.status as it is table joined with users on user_id) but on stack overflow someone helped me with this (view file):
<th><%= user.job_app.status %></th>
undefined method 'job_apps'
This #job_apps = job_apps.find(params[:id]) is wrong. You need to use the classname when writing a ActiveRecord query. Th below should work
#job_apps = JobApp.find(params[:id])

undefined method `empty?' for nil:NilClass how to avoid it

Hi Together I've got this code:
#coursesFound = #user.available_courses
#courses = []
for course in #coursesFound do
#courseInGroups = course.user_groups
for group in #courseInGroups do
#group = UserGroup.find group.id
if #group.users.map { |u| u.id }.include? #user.id
#courses << course
break
end
end
end
# Wenn ein Kurs keiner Gruppe hinzugefügt wurde
if #courseInGroups.empty?
#courses << course
end
on my debian vm it works fine but on my live system I got this error:
undefined method `empty?' for nil:NilClass
How can I avoid this?
If this #coursesFound = #user.available_courses returns an empty activerecord relation.
Then this won't execute
for course in #coursesFound do
#courseInGroups = course.user_groups
for group in #courseInGroups do
#group = UserGroup.find group.id
if #group.users.map { |u| u.id }.include? #user.id
#courses << course
break
end
end
end
Which means when you get here #courseInGroups is nil
if #courseInGroups.empty?
#courses << course
end
So your quick fix would be
if #courseInGroups && #courseInGroups.empty?
#courses << course
end
You can use the try method to Avoid this error:
#courseInGroups.try(:empty?)
This won't throw an error if #courseInGroups was nil.
And don't forget blank? when using rails. Here you find a good overview of all methods with or without rails.
I did not analyze your code, it's just for you, me and others that do not use this methods often, mix them up and then come here - just to remember: empty? is not blank?.
You need to properly initialize your object as well.
#courseInGroups = course.user_groups || []
You won't get nil:NilClass error any more if you initialize properly.
To get rid of nil:NilClass error you can use other answer. like try etc.
You can put the ? before the dot of the empty:
if #courseInGroups?.empty

rails 3 - Help Returning a nil

Hello I have the following in my Create Controller:
def create
#requestable = find_requestable
if !#requestable.nil?
. ..
And then:
def find_requestable
params.each do |name, value|
if name =~ /(.+)_id$/
return $1.classify.constantize.find(value)
end
end
nil
end
this works find when find_requestable sends back a paratemter, but if it doesn't it's not sending back a NIL which causes everything to error with:
NameError (uninitialized constant Undefined):
app/controllers/request_threads_controller.rb:133:in `find_requestable'
app/controllers/request_threads_controller.rb:131:in `each'
app/controllers/request_threads_controller.rb:131:in `find_requestable'
app/controllers/request_threads_controller.rb:52:in `create'
app/middleware/flash_session_cookie_middleware.rb:14:in `call'
Why isn't find_requestable sending back nil? thank you
Third line of your find_requestable method, first check to see if name is blank. Give that a shot.
if !name.blank? && name =~ /(.+)_id$/
UPDATE: Answer in Comment:
The only other thing I can think of is that one of your params has Undefined as its value, which is causing return $1.classify.constantize.find(value) to throw up. Can you take a look at the HTTP Headers and the POST parameters that are being sent across the wire?

Resources