testing for non-existent parameters with "if"

Taylor Strait wrote:

Rails gives me an error when I test for a blank param like this:

        if params[:post][:id]           @comment.commentable = Post.find(params[:post][:id])         elsif params[:event][:id]           @comment.commentable = Event.find(params[:event][:id])         end

If I have params[:post][:id], things are fine. But if I have params[:event][:id] instead, I get this error:

You have a nil object when you didn't expect it! You might have expected an instance of Array. The error occurred while evaluating nil.

Rails dies when it checks for the non-existent params[:post][:id]. I will always send either :event or :post, but never both. How can I use "if - elsif" to test for this without crashing? Thanks!

It depends on what is nil, i.e. params[:post] or params[:post][:id] but you can do something like:

if params[:post].has_key?(:id)

or

if not params[:post][:id] == nil