Capitalize f.text_field

限于喜欢 提交于 2019-12-05 05:07:24

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!