I have a form_for and I want that any value inside x.textField appear with the first letter in Upcase (I'm talking about the edit where the textfield are prefilled by the db values).
You can capitalize it like this:
<%= form_for ... do |f| %>
<%= f.text_field :name, :value => f.object.name.capitalize %>
You can do this with CSS...
= f.text_field :some_attribute, style: 'text-transform: capitalize;'
Pan Thomakos's solution will work, but if you don't want to have to add :value => f.object.name.capitalize
to every text field on the form, you could look into writing your own FormBuilder.
Put this somewhere in your load path, like lib/capitalizing_form_builder.rb
class CapitalizingFormBuilder < ActionView::Helpers::FormBuilder
def text_field(method, options = {})
@object || @template_object.instance_variable_get("@#{@object_name}")
options['value'] = @object.send(method).to_s.capitalize
@template.send(
"text_field",
@object_name,
method,
objectify_options(options))
super
end
end
Usage:
<% form_for(@post, :builder => CapitalizingFormBuilder) do |f| %>
<p>
<%= f.text_field :title %>
</p>
<p>
<%= f.text_field :description %>
</p>
<p>
<%= f.submit 'Update' %>
</p>
<% end %>
you can also do this in controller's create/update action like as given below
def create
@user = User.new(params[:user])
@user.name = params[:user][:name].capitalize
if @user.save
#do something
else
#do something else
end
end
来源:https://stackoverflow.com/questions/4951202/capitalize-f-text-field