Вопрос

Trying to title-case all the entries from a form_for field so they're consistent going into the database for searches.

Here is my search field (file created as a partial):

<%= form_for @airport do |f| %>  
Input city  
<%= f.text_field :city, :value => f.object.city.titlecase %>  
Input country  
<%= f.text_field :country, :value => f.object.country.titlecase %>  
<%= f.submit %>  
<% end %>

But when I run it I get a NoMethodError:

undefined method 'titlecase' for nil:NilClass

I took instruction on the .object.city.titlecase from this post.

Can anyone help?

Это было полезно?

Решение

You don't want to take care of normalizing your data in a view - what if the user changes the data that gets submitted? Instead you could take care of it in the model using the before_save (or the before_validation) callback. Here's an example of the relevant code for a model like yours:

class Place < ActiveRecord::Base
  before_save do |place|
    place.city = place.city.downcase.titleize
    place.country = place.country.downcase.titleize
  end
end

You can also check out the Ruby on Rails guide for more info.


To answer you question more directly, something like this would work:

<%= f.text_field :city, :value => (f.object.city ? f.object.city.titlecase : '') %>  

This just means if f.object.city exists, display the titlecase version of it, and if it doesn't display a blank string.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top