Reputation: 3298
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
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
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