NoMethodError (undefined method `last' for true:TrueClass): - ruby-on-rails

I got NoMethodError (undefined method `last' for true:TrueClass):
from app/controllers/posts_controller.rb:71:in `uploads'
Here is the script
def uploads
#post = current_user.posts.friendly.find(params[:id])
a = #post.images.attach(params[:file])
render json: {url: url_for(a.last)}
end
Not sure what am I doing wrong. Any advice?

I imagine the 'attach' method is returning 'true' or 'false' as to whether it was successful or not rather than assigning the file to the variable.
Personally I'd remove the variable 'a', then just use:
url_for(#post.images.last)

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

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.

NoMethodError - undefined method for nil:NilClass:

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

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

Resources