Timothy
Timothy

Reputation: 15

Rails 3 text_field with :placeholder submitting as not nil

I have a Rails 3 form which is using the following basic syntax:

<%= form_for(:cont, :url => {:action => 'update', :id => @cont.id}) do |f| %>
    <%= render(:partial => 'form', :locals => {:f => f}) %>
    <%= submit_tag("Update", :class => 'submit') %>
<% end %>

Where the partial looks similar to:

<%= f.label(:name) %><%= f.text_field(:name, :placeholder => 'John Doe', :title => 'First and Last Name' %>
<%= f.label(:optional_description) %><%= f.text_field(:optional_description, :placeholder => 'not required', :title => 'Seriously, its optional' %>

When the form is submitted with the "name" properly inputted (and validated in the model) and the "optional_description" left with the default placeholder text, the POST request submits something similar the following:

POST /cont/update/1
...
name=Jane%20Smith&optional_description=

When the params[:cont] are taken, this value is not listed as nil, but rather having something similar to '' as the value. When the record is updated, the value returned is '', which does not satisfy the nil requirement.

How do I prevent the form from submitting optional input fields with only the placeholder text as the values?

Is the best way to fix this just removing it from the params at the controller level?

Much appreciated

Upvotes: 0

Views: 1227

Answers (1)

Azolo
Azolo

Reputation: 4383

I would probably do it in the model

def optional_description=(optional_description)
  optional_description = nil if optional_description.blank?
  super(optional_description)
end

This is a little better than doing it in the controller.

Upvotes: 1

Related Questions