Posts tagged "rails 3"

I’m pleased to say that we released SimpleForm 1.4. Like the last version, this release had a lot of contributions from the community, closing bugs and adding some nice features. Here is a brief introduction to some of the new features:

Custom Form Builders

Now you can set a custom form builder that inherits from SimpleForm::FormBuilder:

class CustomBuilder < SimpleForm::FormBuilder
  def input(attribute_name, options={}, &block)
    options[:input_html].merge! :class => 'custom'
    super
  end
end

And use it straight in the simple_form_for helper, like the example below:

<%= simple_form_for(@user, :builder => CustomBuilder) do |f| %>
  <%= f.input :name %>
<% end %>

Custom Inputs

SimpleForm has many different inputs available in its source code. But, sometimes, depending on the business logic the application requires, we need to add new inputs to make our work easier. Before this version, you had to explicitly define your new input inside SimpleForm namespace for it to work. Furthermore, customizing existing SimpleForm inputs could only be achieved through monkey patching.

Inspired by a similar feature in the Formtastic gem, from now on you will be able to create new input types inside app/inputs folder in your application. The only restriction to create such inputs is that the class name must end with Input. See some examples:

# app/inputs/currency_input.rb
class CurrencyInput < SimpleForm::Inputs::StringInput
  def input
    "$ #{super}".html_safe
  end
end

And the usage:

f.input :money, :as => :currency

You can also redefine existing SimpleForm inputs by creating a new class with the same name. For instance, if you want to wrap date/time/datetime inputs in a div, you can do:

# app/inputs/date_time_input.rb
class DateTimeInput < SimpleForm::Inputs::DateTimeInput
  def input
    "<div>#{super}</div>".html_safe
  end
end

HTML 5

SimpleForm allows you to add many HTML 5 features to your applications, like placeholders, inline browser validations and more. The problem is: most browsers are still experimenting some HTML 5 features, and people started having lots of troubles with the automatic browser validation.

For this reason, SimpleForm now has an option to easily disable such form validations. You have to add this line to your SimpleForm initializer:

config.browser_validations = false

But, if HTML 5 is still not for you, you can disable all the HTML 5 stuff, by adding the configuration below to your initializer:

config.html5 = false

Notice that this option does not disable the `placeholder` component, because we believe this option is very well supported currently in mostly browsers. If you don’t want to use it as well, just remove it from the `components` option in your initializer.

More Helpers

In this version we also add two new form helpers to SimpleForm: input_field and full_error.

The full_error helper shows errors in an attribute prepending its human name. This can be used when you want to show errors on hidden fields, for instance. You can see how it works in this example:

f.full_error :token #=> <span class="error">Token is invalid</span>

The input_field helper renders only the input tag with all the facilities of SimpleForm’s input helper. It means no wrapper, error or hint will be rendered. A good example of using this helper is inside an input block:

<%= f.input :max_time, :as => :integer do %>
  <%= f.input_field :max_time, :as => :integer, :type => :range %>
  <%= content_tag :span, '1', :id => 'max_time_value' %>
<% end %>

It will render:

<div class="input integer required">
  <label class="integer required for="model_max_time">Max time <abbr title="required">*</abbr></label>
  <input class="numeric integer required" id="model_max_time" name="model[max_time]" required="required" size="50" type="range" />
  <span id="max_time_value">1</span>
</div>

Wrapping up

This version allows you to do more customizations in SimpleForm based on your applications needs. We encourage you to take a look at the CHANGELOG and also review the README to see what else is available and some more examples.

And please, check out SimpleForm contributors, we want to thank everyone who is helping us to improve SimpleForm.

Right now, we are working on Rails 3.1 compatibility for the next version. If you feel like helping us or just want to see a new feature, feel free to send us a pull request. And last, but not least, we look forward to know how SimpleForm is changing your life. Is it being helpful? How does it improve your applications? Don’t be shy, comments are welcome.

It is common in Rails 3.0 applications that you want to provide default views for a group of controllers. Let’s say you have a bunch of controllers inside the Admin namespace and you would like each action to fallback to a default template. So if you are rendering the index action for Admin::PostsController and “app/views/admin/posts/index.html.*” is not available, it should then render “app/views/admin/defaults/index.html”.

There are several ways to implement this feature at the controller level. It mainly relies on trying to render the original template and then rescue ActionView::MissingTemplate. If this error is rescued, you then render the default one. However, there is a considerable performance overhead in this approach as it needs to pass through the rendering and template lookup stack twice.

Luckily, since Rails 3.0, we have a new abstraction called resolvers that holds the logic to find a template. I explain comprehensively how resolvers work and their API in my book Crafting Rails Applications. So here I would just show the basics to get this functionality working.
First, we need to define a DefaultResolver, it could be done inside the lib directory:

class MyResolver < ::ActionView::FileSystemResolver
  def initialize
    super("app/views")
  end
 
  def find_templates(name, prefix, partial, details)
    super(name, "admin/defaults", partial, details)
  end
end

Our new resolver simply inherits from ActionView::FileSystemResolver and does two changes: Overrides the initialize method so the view path defaults to “app/views” inside our application and overrides find_templates. The find_templates method receives the template name, a prefix (i.e. the controller path), a boolean marking if the template is a partial or not and a hash of details. In the example above, we simply ignore the prefix given and hardcode it to “admin/defaults”.

Now, assuming that all controllers inside the Admin namespace inherit from an Admin::ApplicationController, we can add default views to all of them by adding the following line:

class Admin::ApplicationController < ActionController::Base
  append_view_path MyResolver.new
end

And we are done! The view_paths holds a list of paths and/or resolvers that the controller will look for templates until one is found. If none is found, an ActionView::MissingTemplate is raised. Since we used append_view_paths, our resolver was added after the “app/views” path, used by default in all controllers.

As you may have guessed, resolvers are a powerful abstraction that allows you to retrieve templates from anywhere, including the database, which is the example given in Crafting Rails Applications.

Finally, template inheritance was a feature recently added to Rails master (upcoming Rails 3.1), so you won’t need to create your custom resolver as above. There is a good wrap up about this feature in Rails Edge.

We have been working on SimpleForm for some time since the last release and have got a lot of contributions from community. Now it is time for a new release with more HTML 5 compatibility plus some new cool features. So, without further ado, lets take a ride on the new stuff.

HTML 5

One of the most useful features coming in HTML 5, in my opinion, is the placeholder option. This option allows us to configure a text to be shown inside the input when it is empty. This is really nice to help the user while filling out forms. SimpleForm now gives us the possibility to pass in a placeholder option in the same way we are used to do with use hints:

<%= simple_form_for @user do |f| %>
  <%= f.input :username, :label => 'Your username please' %>
  <%= f.input :password, :hint => 'No special characters.' %>
  <%= f.input :email, :placeholder => 'user@domain.com' %>
  <%= f.button :submit %>
<% end %>

As you can see here, the placeholder is given as String, but it can also be fetched from I18n, as labels/hints does.

Another addition is the automatic lookup of min/max values from numericality validations, for number inputs. For instance:

class User
  validates_numericality_of :age, :greater_than_or_equal_to => 18,
    :less_than_or_equal_to => 99, :only_integer => true
end
<%= simple_form_for @user do |f| %>
  <%= f.input :age %>
<% end %>

Would generate an input with type number, and the min/max attributes configured with 18 and 99, respectively.

Besides that SimpleForm also adds:

  • the :required html attribute for required inputs (it is retrieved automatically from your presence validations);
  • the :search and :tel input types, with :tel mapping automatically for attributes matching /phone/.

Collections

From now on, radio and check box collections will wrap the input element inside the label, making it pretty straightforward to associate both elements. Besides that, SimpleForm now comes with two new configurations:

  • collection_wrapper_tag wraps the entire collection in the configured tag;
  • item_wrapper_tag wraps each item in the collection using the configured tag.

An example:

<%= simple_form_for @user do |f| %>
  <%= f.association :roles, :as => :check_boxes, 
    :collection_wrapper_tag => :ul, :item_wrapper_tag => :li %>
<% end %>

This should be kind of self explanatory =).

New input options

It’s now possible to give the :disabled option straight to the input, which will also add the disabled css class to both input and wrapper elements:

<%= simple_form_for @user do |f| %>
  <%= f.input :email, :disabled => true %>
<% end %>

And also the :components option, which will only render the given components in the given order:

<%= simple_form_for @user do |f| %>
  # Generates the label after the input, and ignores errors/hints/placeholders
  <%= f.input :email, :components => [:input, :label] %>
<% end %>

New configuration options

If you are not using any label / hint / placeholder with I18n, you can now completely disable the translation lookup of these components by setting the config.translate to false in your SimpleForm initializer. This should improve performance a bit in these cases.

Another nice improvement is the ability to add custom input mappings to SimpleForm. If you ever needed to map a specific attribute to a default input, now you can:

  config.input_mappings = { /_count$/ => :integer }

This configuration expects a hash containing a regexp to match as key, and the input type that will be used when the field name matches the regexp as value. In this example we match all attributes ending with _count, such as comments_count, to be rendered as integer input by SimpleForm.

New docs and mailing list

SimpleForm now has its own google group where you can ask questions, search for already answered questions and also help others. Besides that, you can also navigate and search the entire RDoc.

Wrapping up

As you can see, there are plenty of new and cool stuff in this release. We encourage you to take a look at the CHANGELOG and also review the README to see what else is available and some more examples.

And please, check out SimpleForm contributors, we want to thank everyone who is helping us to improve SimpleForm.

What about you? Do you want any cool feature in SimpleForm? Help us improve it by forking and sending us a pull request, we will be really glad to apply it. We hope to see your name in the contributors page soon!

Finally, in your opinion, what is the coolest feature SimpleForm has? And what idea you have you might want to be added to SimpleForm? Feel free to comment :D

A couple weeks ago we finally released Devise 1.1 which is fully-compatible with Rails 3! Not only that, we’ve been working with Rails 3 since the first betas and several features were added along the way! Let’s take a look at those, some architectural changes and see how Devise 1.1 and Rails 3 will change how you handle authentication.

Pretty URLs with Metal

A common complaint in Devise 1.0 (for Rails 2.3) was, in order to know which message to show to the user when sign in failed, we had to pass a parameter in the URL as in /users/sign_in?unauthenticated=true while one would expect us to simply use flash messages. This happened because the redirection was done not from inside a controller, but a Rack application set up in Warden (a Rack authentication framework Devise relies on) and we could not access flash messages from it.

However, since Rails 3 moved several responsibilities to the Rack layer, including flash messages, we can easily access flash messages from any Rack application, allowing us to remove the parameter from the URL! Even more, Rails 3 provides small, fast, bare bone controllers through ActionController::Metal, which we used in Devise to clean and speed up the code considerably.

Locking goodness

The lockable module in Devise also went through a major overhaul. Previously, it already supported :unlock_strategy as option, allowing you to specify if the user could be automatically unlocked after a time period, through an e-mail token or both. Now, it also supports :none as option, meaning that all unlocking should be done manually.

Even more, there is a new option called :lock_strategy, that allows you to specify whether the lock happens only manually or after an amount of invalid sign in attempts.

HTTP Authentication on by default

In Devise 2.3, you may remember that we had a module called :http_authenticable along with :database_authenticatable and :token_authenticatable. While all three worked great, it was confusing that all HTTP authentication features were built on top of the database authentication and it was not possible to do HTTP authentication using a token unless we created a forth module called :http_token_authenticatable. We quickly noticed this could be improved by providing a better design and better abstract Devise authentication strategies.

And that is what happened in Devise 1.1. Now both database and token authentication work through HTTP with no extra work and the http authenticatable module was deprecated. Besides, if you are creating a new strategy on your own, you get both authentication through parameters (form) and HTTP with no extra work!

Routing customizations

We built Devise to be a full stack solution with customization in mind. In Devise 1.1, the customization abilities from Devise were taken to the next level. Now the devise_for method in routes accepts to extra options: :skip and :controllers. The first one allows you to skip the routes generation for a given controller/module in case you want to define them on your own, while the second allows you to change the router to point to a given controller in your application, like Users::ConfirmationsController instead of Devise’s internal controller.

Talking about Devise’s internal controller, Devise 1.1 namespaced all controllers classes, so now we have Devise::ConfirmationsController instead of ConfirmationsController.

Another limitation removed from Devise in this new version is related to URLs customizations. In prior versions, Devise used the URL to retrieve which scope is being accessed. That said, if you were accessing “/users/sign_in”, Devise had to inspect this URL and find the “/users” bit to specify the current scope is “users”. The same happened to “/admin/sign_in”.

This had a huge impact in URL customization, because if you wanted to have an URL like “/some_prefix/users/sign_in”, you had to tell Devise you were appending a prefix. Things could get even uglier if you wanted to prepend dynamic prefixes like “/:locale”.

In Devise 1.1, we use the new contraints API and Rack capabilities from the new router to specify which scope to use. So, instead of inspecting the URL, Devise retrieves the user from the request’s env hash as request.env["devise.mapping"].

For all the routes generated by devise_for, Devise automatically sets this value in the env hash. However, if you are creating your own routes, you need to set it manually using the constraints API:

constraints lambda { |r| r.env["devise.mapping"] = Devise.mappings[:user] } do
  # Add a custom sign in route for user sign in
  get "/sign_in", :to => "devise/sessions"
end

Of course, since this is rather a common pattern, we encapsulated it in a nice API:

devise_scope :user do
  # Add a custom sign in route for user sign in
  get "/sign_in", :to => "devise/sessions"
end

You can simply give a block to devise_for as well and get the same result:

devise_for :users do
  # Add a custom sign in route for user sign in
  get "/sign_in", :to => "devise/sessions"
end

All the routes specified in the block have higher priority than the ones generated by devise_for.

Awesomeness pack

The last feature we want to discuss is also a routing customization, but we decided to leave it up for last because it shows all the potential coming with Rails 3 and Devise 1.1.

In Devise 1.1, we added the ability to require authentication for a given url in the router, besides the existing before filters in controllers. This allow us to easily require authentication for third party rack application without a need to hack into them. Kisko Labs posted an interesting case where you can use Devise to require authentication to a Resque application in very few lines of code:

authenticate :admin do
  mount Resque::Server.new, :at => "/resque"
end

Devise simply uses the constraints API discussed above, allowing the request to continue only if the user is already authenticated. Otherwise, it redirects the admin to the sign page managed by Devise inside your Rails application. Indeed, when you have Rack, Rails 3 and Devise 1.1 playing along, great things can be accomplished quite easily!

There are several other features, bug fixes and deprecations included in this release, we invite you to check the CHANGELOG and take a look at them!

And we are happy to say this is not all, there is much more to come in Devise 1.2, including OAuth2 support which is already added in the master branch. Enjoy!

You probably know that Active Record got a facelift and is now powered by Active Relation. A new chainable-award-winning-lazy API was added and received great feedback! However, as more and more people are trying Rails 3 beta, a small incompatibility between the old and new syntax was found. This post explains this incompatibility and how it was solved.

The issue

Quoting the Lighthouse ticket, imagine the following scenario in Rails 2.3:

class Page < ActiveRecord::Base
  default_scope :conditions => { :deleted_at => nil }
 
  def self.deleted
    with_exclusive_scope :find => { :conditions => "pages.deleted_at IS NOT NULL" } do
      all
    end
  end
end

If you rewrite it to the new 3.0 syntax, your first attempt would probably be:

class Page < ActiveRecord::Base
  default_scope where(:deleted_at => nil)
 
  def self.deleted
    with_exclusive_scope :find => where('pages.deleted_at IS NOT NULL') do
      all
    end
  end
end

However, if you try it out on console, you will find out it does not work as expected:

Page.all         #=> SELECT "pages".* FROM "pages" WHERE ("pages"."deleted_at" IS NULL)
Page.deleted.all #=> SELECT "pages".* FROM "pages" WHERE ("pages"."deleted_at" IS NULL) AND ("pages"."deleted_at" IS NOT NULL)

To understand why it does not work, let’s take a look at the source code!

Investigating the issue

With Active Relation, Active Record is no longer responsible to build queries. That said, ActiveRecord::Base is not the one that implements where() and friends, in fact, it simply delegates to an ActiveRecord::Relation object. From ActiveRecord::Base source code:

delegate :select, :group, :order, :limit, :joins, :where, :preload, :eager_load, :includes, :from, :lock, :readonly, :having, :create_with, :to => :scoped

And the scoped implementation is shown below:

def scoped(options = nil)
  if options.present?
    scoped.apply_finder_options(options)
  else
    current_scoped_methods ? relation.merge(current_scoped_methods) : relation.clone
  end
end
 
def relation
  @relation ||= ActiveRecord::Relation.new(self, arel_table)
  finder_needs_type_condition? ? @relation.where(type_condition) : @relation
end

As you can see, scoped always returns an ActiveRecord::Relation that you build your query on top of (notice that ARel::Relation is not the same as ActiveRecord::Relation).

Besides, if there is any current_scoped_methods, the scoped method is responsible to merge this current scope into the raw relation. This is where things get interesting.

When you create your model, current_scoped_methods returns by default nil. However, when you define a default_scope, the current scope now becomes the relation given to default_scope, meaning that, every time you call scoped, it returns the raw relation merged with your default scope.

The whole idea of with_exclusive_scope is to be able to make a query without taking the default scope into account, just the relation you give in as argument. That said, it basically sets the current_scope_methods back to nil, so every time you call scoped to build your queries, it will be built on top of the raw relation without the default scope.

With that in mind, if we look again at the code which we were trying to port from Rails 2.3, we can finally understand what was happening:

def self.deleted
  with_exclusive_scope :find => where('pages.deleted_at IS NOT NULL') do
    self
  end
end

When we called where('pages.deleted_at IS NOT NULL') above, we were doing the same as: scoped.where('pages.deleted_at IS NOT NULL'). But, as scoped was called outside the with_exclusive_scope block, it means that the relation given as argument to :find was built on top of default_scope explaining the query we saw as results.

For example, the following syntax would work as expected:

def self.deleted
  with_exclusive_scope do
    where('pages.deleted_at IS NOT NULL').all
  end
end

Since we are calling where inside the block, the scoped method no longer takes the default scope into account. However, moving the relation inside the block is not the same as specifying it to :find, because if we were doing three queries inside the block, we would have to specify the same relation three times (or refactor the whole code to always do a query on top of this new relation).

That said, it seems the previous with_exclusive_scope syntax does not suit very well with ActiveRecord’s new API. Maybe is it time for change? Can we provide a better API? Which are the use cases?

Identifying the use cases

The with_exclusive_scope method has mainly two use cases. The first one, which we just discussed above, is to allow us to make a query without taking the default scope into account inside our models:

def self.deleted
  with_exclusive_scope do
    where('pages.deleted_at IS NOT NULL').all
  end
end

While this code looks ok, if we think about relations, we will realize that we don’t need to give a block to achieve the behavior we want. If the scoped method returns a raw relation with the default scope, couldn’t we have a method that always returns the raw relation? Allowing us to build our query without taking the default scope into account?

In fact, this method was already implemented in Active Record and it is called unscoped. That said, the code above could simply be rewritten as:

def self.deleted
  unscoped.where('pages.deleted_at IS NOT NULL').all
end

Much simpler! So, it seems that we don’t need to support the block usage at all, confirm?

Deny! Going back to the Page example above, it seems we should never see deleted pages, that’s why we set the default_scope to :deleted_at => nil. However, if this application has an admin section, the admin may want to see all pages, including the deleted ones.

That said, what we could do is to have one controller for the normal User and another for the Admin. In the former, we would always use Page.all, and Page.unscoped.all in the latter.

However, if these controllers and views are very similar, you may not want do duplicate everything. Maybe it would be easier if we do something like this:

def resource_class
  if current_user.is_admin?
    Page.unscoped
  else
    Page
  end
end

And, instead of always referencing the Page class directly in our actions, we could call resource_class. While this solution is also ok, there is a final alternative, that would require no changes to the current code. If you want to use the same controller for different roles, but changing the scope of what they are allowed to see, you could simply use an around_filter to change the model scope during the execution of an action. Here is an example:

class PagesController < ApplicationController
  around_filter :apply_scope
 
  # some code ...
 
  protected
 
  def apply_scope
    if current_user.admin?
      Page.with_exclusive_scope { yield }
    else
      yield
    end
  end
end

That said, being allowed to give a block to with_exclusive_scope is actually useful and since we want to deprecate with_exclusive_scope in favor of unscoped in the future, we brought this very same syntax to unscoped as well:

def apply_scope
  if current_user.admin?
    Page.unscoped { yield }
  else
    yield
  end
end

Tidying it up

Well, after the behavior in with_exclusive_scope was properly ported to the new API, we need to be sure we are not forgetting about anything… wait, actually we are.

with_exclusive_scope has an evil twin brother called with_scope which behaves very similarly, except that it always build the query on top of the scoped relation. It works like this:

class Page < ActiveRecord::Base
  default_scope where(:deleted_at => nil)
end
 
Page.with_scope :find => { :conditions => { :active => true } } do
  Page.all #=> Bring all active pages that were not deleted
end

However, this feels way too hash-ish. Of course, we could use relations to make it a bit prettier:

Page.with_scope :find => where(:active => true) do
  Page.all #=> Bring all active pages that were not deleted
end

This is ok, but it seems that we could improve it even more. That said, we added a new method to relations, called scoping:

Page.where(:active => true).scoping do
  Page.all #=> Bring all active pages that were not deleted
end

Yeah! Sign me up ’cause this looks way better than the previous syntax! And, if you check the original commit, you will notice the unscoped method with a block simply delegates scoping:

def unscoped
  block_given? ? relation.scoping { yield } : relation
end

So, with unscoped and scoping implemented, we just need to commit, git push and be happy, confirm? Deny! There is one last case to check.

create_with

If you payed attention properly, you can notice that every time we called with_exclusive_scope and with_scope, we always passed { :find => relation } as hash, instead of simply giving the relation. This happens because these methods accept two hash keys: find and create.

As you may expect, one specifies the behavior for create and the other for finding. In most of the cases, they are exactly the same and work with the new syntax:

page = Page.where(:active => true).new
page.active #=> true

However, for obvious reasons, this only works if the conditions are given as a hash. Consider this case:

page = Page.where("active = true").new
page.active #=> nil

That said, there may be a few scenarios where you want to specify the creation conditions on its own, explaining the :find and :create options in with_exclusive_scope and with_scope methods. So, how can I achieve it with the new syntax? Easy!

page = Page.create_with(:active => true).new
page.active #=> true

If you provide both conditions as a hash and create_with, create_with always have higher priority:

page = Page.where(:active => false).create_with(:active => true).new
page.active #=> true

Note this syntax already existed, we are just making it explicit now as part of the new API! That said, commit, push and be happy!

Wrapping up

All in all, with_exclusive_scope and with_scope are now part of the old ActiveRecord API giving place to the new, strong and vibrant unscoped and scoping methods!

However, they are not going to be deprecated now. They will follow the same deprecation strategy as all the current methods.

And you? What do you think about this new scoping API?

Sometime ago we were working on a project together with a designer, and that specific application was full of forms, each one having a different layout, but most of them sharing the same features: inline errors, hints, specific label markup for required fields, etc. To start prototyping the application faster, we used the markup the designer created with similar forms, duplicating the code. But we don’t like code duplication, we weren’t feeling comfortable with it. So we decided to move on and create a tool to help us, that should be flexible enough to let us define the markup that fits better for each application, or even no extra markup at all. Here is SimpleForm!

SimpleForm inputs

From the README:

Forms made easy (for Rails)!

SimpleForm aims to be as flexible as possible while helping you with powerful components to create your forms. The basic goal of simple form is to not touch your way of defining the layout, letting you find the better design for your eyes. Good part of the DSL was inherited from Formtastic, which we are thankful for and should make you feel right at home.

As the README says, SimpleForm is a tool to help you build forms easily in Rails. Let’s see some examples:

<%= simple_form_for @user do |f| %>
  <%= f.input :username, :label => 'Your username please' %>
  <%= f.input :password, :hint => 'No special characters.' %>
  <%= f.input :remember_me, :as => :boolean %>
  <%= f.button :submit %>
<% end -%>

There are plenty of things going on here: we create a form using simple_form_for helper, then we use the :input method to create input elements based on column type. For instance, :username will create a default text input, while :password attribute will render an input type password. For the :username attribute, we are specifying a label manually. For :password, the label will be taken from I18n, and we are adding a hint message to the field. For :remember_me, we are explicitly saying to render it as a checkbox, using the :as => :boolean option (that is the default for boolean attributes). Also, there is a button helper that simply delegates to Rails helpers, in this case submit.

The output for a new @user would be:

<form action="/users" class="simple_form user" id="new_user" method="post">
  <div class="input string required">
    <label class="string required" for="user_username"><abbr title="required">*</abbr> Your username please</label>
    <input class="string required" id="user_username" maxlength="255" name="user[username]" size="50" type="text" />
  </div> 
  <div class="input password required">
    <label class="password required" for="user_password"><abbr title="required">*</abbr> Password</label>
    <input class="password required" id="user_password" name="user[password]" size="30" type="password" />
    <span class="hint">No special characters.</span>
  </div> 
  <div class="input boolean optional">
    <label class="boolean optional" for="user_remember_me"> Remember me</label>
    <input name="user[remember_me]" type="hidden" value="0" />
    <input class="boolean optional" id="user_remember_me" name="user[remember_me]" type="checkbox" value="1" />
  </div> 
  <input id="user_submit" name="commit" type="submit" value="Create User" /> 
</form>

You may have noticed there is some additional css classes added to the markup, like string and required. They are added automatically by SimpleForm to help us style and plug some javascript in. There are specific css classes for each available input type. Also, pay some attention to the label: inside it there is an abbr tag with an asterisk (*) showing that the field is required. SimpleForm uses the new validations reflection API from Rails 3 to check if the attribute has the presence validator, and mark the field as required if so. And we are able to say that a field is required or disable the required mark, by passing the option :required => true|false.

Furthermore, there is the hint tag for the :password attribute that SimpleForm creates based on the :hint option we have defined. Also notice that the gem has automatically added a div wrapper to each input, with the same css classes. SimpleForm allows us to configure this wrapper as well, using for instance p instead of div. We are going to see more about configuration later.

SimpleForm is already prepared to generate some of the new HTML 5 input tags, such as email, url and number inputs:

<%= simple_form_for @user do |f| %>
  <%= f.input :website, :as => :url %>
  <%= f.input :email %>
  <%= f.input :age, :hint => "This defaults to 'number' input based on field type" %>
  <%= f.button :submit %>
<% end -%>

Based on the attribute name, SimpleForm will generate url or email input types, and we can always set a specific type with the :as option. Numeric attributes will always be rendered as input type number.

Working with associations

SimpleForm adds a custom and straightforward method to render select tags for associations, called association. For now, consider our User belongs to a Company, and has and belongs to many Roles. Let’s go straight to the example:

<%= simple_form_for @user do |f| %>
  <%= f.input :name %>
  <%= f.association :company %>
  <%= f.association :roles %>
  <%= f.button :submit %>
<% end -%>

It will detect the association type and render a select tag for choosing the company, listing all companies in the database, and another select for roles, with multiple option enabled.

SimpleForm also has some add-ons, letting us render associations as a collection of radios or check boxes. Using the same example:

  f.association :company, :as => :radio
  f.association :roles, :as => :check_boxes

Now we are rendering a collection of radios for choosing the Company, and another collection of check boxes for choosing Roles.

Configuration

SimpleForm lets us do some customizations by running its install generator:

rails generate simple_form:install

# Output
  create  config/initializers/simple_form.rb
  create  config/locales/simple_form.en.yml
  create  lib/templates/erb/scaffold/_form.html.erb

As we can see, running this generator will copy an initializer file, responsible for configuring SimpleForm; a locale file, to let us change some I18n messages; and a form template inside our lib dir. This template will be used instead of the default Rails scaffold form template, so it will create our form already using SimpleForm. Easy, right?

Let’s take a look at some configuration options:

  • components: defines the components used by the form builder. We can remove any of them, change the order, or add new ones. Defaults to [ :label, :input, :hint, :error ].
  • hint_tag: tag used for hints, defaults to span.
  • error_tag: tag used for errors, defaults to span.
  • wrapper_tag: tag used as wrapper to all inputs, defaults to div
  • label_text: determines how the label text should be generated altogether with the required text. It must be a lambda/proc that receives both label and required texts. Defaults to "required label".

There are a lot more options available in the initializer file, such as default input size and priority countries for generating country selects. Also, the locale file lets us determine the required text and mark, or even the entire required html tag.

Internationalization

SimpleForm is ready for I18n, supporting labels and hints. In addition, it lets us set different content for each action, new and edit. Here is an example locale file:

  en:
    simple_form:
      labels:
        user:
          username: 'User name'
          password: 'Password'
          edit:
            username: 'Change user name'
            password: 'Change password'
      hints:
        user:
          username: 'User name to sign in.'
          password: 'No special characters, please.'

Simple, right? If it does not find any specific translation using I18n for the label, it will fallback to human_attribute_name.

Here we go!

SimpleForm has much more to offer. We would like to invite you to take a better look at the examples and possibilities. Remember, SimpleForm aims to be flexible and powerful to help you easily build forms, without saying how you should create your markup.

Also, feel free to explore the source code and extend SimpleForm even further. Since it’s based on components, creating a new component which moves the current hints to inside the input (using javascript or the new placehoder attribute in HTML 5), should be easy!

It’s worth saying SimpleForm is Rails 3 compatible in the master branch. If you are using Rails 2.3.x, there is a v1.0 branch and version that you might want to take a look.

SimpleForm has been helping us a lot so far, we hope you enjoy it. Moreover, we would like to enjoy other tools that help your productivity day by day, please leave a comment and let us know, we would appreciate a lot!