Cal Peters
Cal Peters

Reputation: 81

Nil check on form params not working

I've integrated a hidden field called nickname which should not be entered, if it is, it suggests a bot is filling it in and therefore should not process the action mailer.

Here's the code I have to do this filter:

if params[:nickname] == nil
  @contact = Contact.create(contact_params)
  if @contact.save
    GenericMailer.contact_mailer(@contact).deliver
  else
    redirect_to root_path alert: "Oops! It looks like you have entered something incorrectly, please try again."
  end
else
  redirect_to root_path
end

Form:

<%= form_for @contact, :url => {:controller => "footerlinks", :action => :contactcreate } do |lead|%>
    <%= lead.text_field :fullname, :placeholder => "Full name", onfocus: "this.placeholder = ''", onblur: "this.placeholder = 'Full name'" %>
    <%= lead.text_field :email, :placeholder => "Email", onfocus: "this.placeholder = ''", onblur: "this.placeholder = 'Email'" %>
    <%= lead.text_area :query, class: "height15", :placeholder => "Query", onfocus: "this.placeholder = ''", onblur: "this.placeholder = 'Query'" %>
    <%= lead.text_field :nickname %>
    <%= lead.submit "Send" %>
<% end %>

However, upon re-trying the form it seems to completely bypass the if statement and deliver the email despite the nickname form field not being nil.

Upvotes: 0

Views: 117

Answers (2)

Nermin
Nermin

Reputation: 6100

You problem is that params[:nickname] is not even there, it means it is nil, you have params[:contact][:nickname]

Try doing

params[:contact][:nickname].blank? # instead of params[:nickname]

Upvotes: 1

Leo Correa
Leo Correa

Reputation: 19839

It may be that the params[:nickname] is not nil but an empty string. Try doing params[:nickname].blank?

Upvotes: 1

Related Questions