Rails error: undefined method `push' for nil:NilClass - ruby-on-rails

So I have the following code:
new = #params[collection.to_s + '_attributes']
old = #model.send collection
if new.nil?
old.clear
else
new_records = new.map { |_, e| e[:id] }
if !new_records.nil? && !old.nil?
old.not_in(id: new_records).destroy_all
end
end
The problem is I didn't use 'push' function anywhere in my code and based on the stacktrace the error occurs when executing:
old.not_in(id: new_records).destroy_all
I'm new to Rails so I hope someone can help me. Thanks in advance!
UPDATE
I ended up using delete_all instead of destroy_all for now. I think it was causing the error. It's working now but it would really be nice if I could find out why it wasn't working with destroy_all.

I don't think not_in is rails command, Instead, try
old.where.not(id: new_records).destroy_all
or, not in can be used like this.
old.where('id NOT IN (?)',new_records).destroy_all

Try:
old.where.not(id: [new_records]).destroy_all
Not in always requires array.

Related

Counting chars in ruby 1.9.3 error

I'm counting string length as shown below:
if(key['name'].to_s.chars.length==0)
key['name']="Others"
end
And on ruby 2.1.8p440 it works, but on ruby 1.9.3p551 it throws following error:
(undefined method `length' for #<Enumerator: "Latency":chars>):
I cannot update 1.9.3 I must change this code.
What’s wrong with more explicit:
key['name'] = "Others" if key['name'].to_s.empty?
that works everywhere?
BTW, in ruby 1.9.3 there is no Enumerable#length there is Enumerable#count. The alias length it received later.
In Ruby 1.9.3 String#chars
Passes each character in str to the given block, or returns an enumerator if no block is given.
So converting it to an array before calling length should solve the issue:
key['name'].to_s.chars.to_a.count == 0 # or size ?
try key['name'].to_s.mb_chars.length . hope this will help u .
You question is tagged with ruby-on-rails which has the blank? and presence methods. With that methods I would write something like:
if key['name'].blank?
key['name'] = 'Others'
end
Or:
key['name'] = 'Others' if key['name'].blank?
Or:
key['name'] = key['name'].presence || 'Others'

Ruby Ternary Operator does not seem to be working on a hash assignment

In the process of learning ruby (I have a java background).
I have assignment statements where the value of one hash[:name_field] is being assigned to another. But the value coming from the hash on the right was sometimes blank. This was crashing my code hence i added the ternary logic with .nil ? etc....
I am surprised though that this doesn't work... The error is :
undefined method `nil' for 1133:Fixnum (NoMethodError)
Below is the code:
people_traffic.each do |person|
person_record = DaysTraffic.new
person_record[:name] = person[:name_filed].nil ? 0 : person[:name_filed]
person_record[:age] = person[:age_field].nil ? 0 : person[:age_field]
person_record.save
end
Why am I getting the (NoMethodError) for the nil?
Thank you!
It should be .nil? (with a question mark) not .nil. So in your case, that would be:
person_record[:name] = person[:name_filed].nil? ? 0 : person[:name_filed]
You can actually write this much simpler like so:
person_record[:name] = person[:name_filed] || 0
Because #to_i turns nil into 0, a good way to write something like this is:
person_record[:age] = person[:age_field].to_i

Rails: Where clause doesn't work in any condition

I'm about to lose my mind due to a simple Rails where query. I simply cannot understand why it does work like 10 lines ago and does not after it. I could not figure out what might be causing the problem
#userID = Token.where(:tokenCode => #tokenReceived)
##init.tokenCode=#tokenReceived+"1" #randomize algorithm required!
#init.tokenCode=#codeGenerated=generate_activation_code()
if #userID.nil?
#newToken=Token.new
#newToken.tokenCode=#codeGenerated
else
#tokenToAdd = "12"
#newToken=Token.where(:userID => "1")
#if #newToken.nil?
#newToken.tokenCode="12"
#end
end
##newToken.save
#init.save
When I make a successful JSON request to 'http://localhost:3000/inits.json' it gives me a page with tons of erros but I think the main error among those are:
<h1>
NoMethodError
in InitsController#create
</h1>
<pre>undefined method `tokenCode=' for #<ActiveRecord::Relation:0x007fc43cb40b88></pre>
What could be the reason? Am I writing the where clause all wrong?
Edit: When I activate the if clause it works. I simply believe the #newToken object is null, however it is almost impossible for me to detect why. There is a data in my Token table with userID 1.
When you do:
#newToken=Token.where(:userID => "1")
You get an ActiveRecord::Relation, but you expect an object. So simply replace it with:
#newToken=Token.where(:userID => "1").first

undefined method `gsub' for nil:NilClass

I'm newvbie in ruby on rails.. I'm having problem with gsub.. I everytime I go to the list of my store page it says "undefined method `gsub' for nil:NilClass"..
here is mycode :
def self.search(search_val, page = 1)
#search_val = search_val.gsub("'", "\\\\'")
search_query = "store_id LIKE '%#{ #search_val }%' OR english_name LIKE '%#{ #search_val }%' OR chinese_name LIKE '%#{ #search_val }%'"
select("jos_store.id, store_id, english_name, chinese_name, store_manager, delivery_area,year, week").joins("LEFT OUTER JOIN (SELECT id as store_replenishment, store, MAX(stock_movement) AS stock_movement FROM jos_store_replenishment GROUP BY store) AS replenishment ON replenishment.store = jos_store.id").joins("LEFT OUTER JOIN jos_stock_movement ON jos_stock_movement.id = replenishment.stock_movement").where(search_query).order("year DESC, week DESC").paginate :page => page, :per_page => 15
end
thanks in advance
A good practice is doing .to_s when you are using string methods.
You can use the & operator on search_val. It allows you to avoid null pointer exceptions without adding additional checks or using to_s to convert a string to a string.
So, you'll have something like this:
#search_val = search_val&.gsub("'", "\\\\'")
You can read more on the safe navigation operator here: http://mitrev.net/ruby/2015/11/13/the-operator-in-ruby/
This means that search_val is in fact nil. You can easily verify this by printing out the value of search_val.
I'm not sure if this is your case, but the same undefined method gsub for nil:NilClass error happened with me after a few rollbacks and migrations.
Then, I restarted the server and works. Maybe this could be the case for some people that reached this topic searching on Google.

rails project using omniauth - stuck on evaluating nil.[] error

I am using omniauth on my rails project to authenticate with facebook.
I am also trying to get the user's current city from omniauth, and that works great when the user has their current city in facebook.
extra:
user_hash:
name: Jeff Turner
location:
name: Oakland, California
but when the user doesn't have anything, I cant set that value
current_city = user_data['location']['name']
error:
You have a nil object when you didn't expect it!
You might have expected an instance of ActiveRecord::Base.
The error occurred while evaluating nil.[]
I can see that no value with those attributes even come back from omniauth
if I try to test for the nil condition
if user_data['location']['name'].blank? == false
current_city = user_data['location']['name']
end
I seem to get the same error on that first line (user_data['location']['name'].blank?)
still cant evaluate nil.
I am pretty new to rails, so I hope I just missed something obvious.
Update
this is what I ended up changing it to and it worked fine. answer below looks like it would work as well
if user_data['location'].nil? == false
if user_data['location']['name'].nil? == false
current_city = user_data['location']['name']
end
end
You can try doing something like this:
current_city = auth.fetch('location', []).fetch('name', nil)
Using fetch.

Resources