Travis Pessetto
Travis Pessetto

Reputation: 3298

How do I skip a piece of code if object is nil in Rails?

I have a piece of code that enables or disables selection lists when the appropriate checkbox is clicked, however if they are all disabled on post it will not send these in a the params list. So I need to execute code only if they exist.

I've used:

if params[:id][:id2].nil?

and

if params[:id][:id2].blank?

also

if params[:id][:id2].empty?

not to mention simply:

if params[:id][:id2]

And all give the same error..."You have a nil object where you weren't expecting it." How can I fix this error?

Upvotes: 1

Views: 2323

Answers (2)

josemota
josemota

Reputation: 984

Probably params[:id] is nil, check for params[:id].nil?.

EDIT: The comments below state correctly that blank? is better if you seek to evaluate against either nil? or empty?.

Upvotes: 7

Victor Moroz
Victor Moroz

Reputation: 9225

Meanwhile

class Object
  def unless_nil(default = nil, &block)
    if nil?
      default
    else
      block[self]
    end
  end
end

allows things like:

id2 = params[:id].unless_nil { |p_id| p_id[:id2] }
id2, id3 = params[:id].unless_nil([0, 0]) { |p_id| [p_id[:id2], p_id[:id3]] }

Upvotes: 0

Related Questions