简体   繁体   中英

Rails error: undefined method `push' for nil:NilClass

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2025 STACKOOM.COM