NoMethodError on nil.each?

Have you ever have to iterate over an array from say the params hash? You probably have added some code to make sure that data exists in the hash element first before doing the loop. This is a cool little trick to help condense some code. Normally I would write this:

if params[:accounts] and params[:accounts].size > 0
  params[:accounts].each do |account|
    # Do something with account here
  end
end

As you can see, kind of ugly. Here is the change:

(params[:accounts] || []).each do |account|
  # Do something with account
end

AHH!!! Much nicer!

Rails TypeError (can’t dump File)

For a while, I kept getting exceptions from my app in the form of "TypeError (can't dump File):". I finally found out that this was caused when I was using active_record_store with something like file_column, attachment_fu, or paperclip. Basically whenever you’re storing a file in session, that was too large for the session, you would experience this issue. Here is how to get around it: Say you have a model like so (This is using file_column):

class Model < ActiveRecord::Base
  file_column :filename
end

Then in your controller you would want to add a line before you redirect off to clear that session:

class Controller < ApplicationController
  def create
    @model = Model.find(params[:model])
    @model.save!
  
    params[:model][:filename] = nil rescue nil # Reset value here
  
    redirect_to models_path(@model)
  end
end

As you can see, I am resetting the filename value on the model. Now it shouldn’t complain that it can’t dump the file. Happy RAILSING!

%d bloggers like this: