Ruby on Rails - Bootstrap / Form_for vs input_groups - How to stop stylish heads

I am playing around with some input fields for my rails project.

I am a bit taken with the first example shown here . I like the little "@" and can use it as a formatting hint for our users.

Their code looks like this:

<div class="input-group">
  <span class="input-group-addon">@</span>
  <input type="text" class="form-control" placeholder="Username">
</div>

      

If I put this in my rails it works great and looks great.

But my form setup works with the form_for function and I have a hard time getting them to play well.

My rails html.erb code looks like this:

<div class="row">
  <div class="col-md-6 col-md-offset-4">
    <%= form_for @request do |f| %>
      <%= render 'shared/error_messages' %>
      <%= f.label :user_id%>
      <%= f.text_field :user_id%>
      <%= f.submit "Begin my request", class: "btn btn-primary" %>
    <% end %>
  </div>
</div>

      

I've tried combining the two pieces of code in different ways, but no effect!

Common constants are that my rails code always comes out with hard rectangular edges (versus smooth bootstrap curves), I can't get add-group-addon to sit comfortably at the end of the input field, it rides higher and lower differently, or sits awkwardly over a large form block etc ... so not on my part. Anyone got it?

In terms of bootstrap related gems, I use:

gem 'bootstrap-sass',       '3.2.0.0'
gem 'sass-rails',           '5.0.0.beta1'

      

+3


source to share


1 answer


The problem you are working with is form_for

using rails FormBuilder

to generate your form and the method text_field

translates to a specific html chunk. You can create another html snippet for it by creating your own form builder. If you decide to use a different gem, for example, simple_form

it becomes even easier as you can simply create additional field types. You can view the documentation for this gem for more information.

class CustomFormBuilder < ActionView::Helpers::FormBuilder
  def text_field_with_addon(name, addon, *args)
    @template.content_tag(:div,
      @template.content_tag(:span, addon, class: 'input-group-addon') +
      @template.text_field(name, *args),
      class: 'input-group')
  end
end

      



Then use it like:

<%= form_for @request, builder: CustomFormBuilder do |f| %>
  <%= render 'shared/error_messages' %>
  <%= f.label :user_id%>
  <%= f.text_field_with_addon :user_id, '@' %>
  <%= f.submit "Begin my request", class: "btn btn-primary" %>
<% end %>

      

+4


source







All Articles