Simple form_for
Moving from Ruby to Ruby on Rails reminds me of that scene in Transformers when Shia Labeouf first realizes his Chevrolet Camaro is actually a giant robot trying to save the world. The powerful and intelligent alien is destroying my well-kept yard. Let’s walk through the most simple uses for this method and keep your garden intact.
For the newbies: forms are input on webpages, like sign in forms. Ruby has a method that called form_for that generates HTML form tags for you. As input, it takes in a template of the model you are creating a form_for. More jargon! OK, a model is the conceptual model for an item you want to work with in computer science. For example, if you have users, you will want a user model to pass around and reference. Models have attributes, like a user might in the real world: a name, an email, or maybe an address. See the picture above for an example.
Let’s say you want to create a new Pokemon.
pokemons_controller#new
@pokemon = Pokemon.new
pokemon/new.html.erb
<%= form_for @pokemon do |f| %>
Get Adames H.’s stories in your inbox
Join Medium for free to get updates from this writer.
No need to give this @pokemon a type or any other attribute, form_for uses the empty template (Pokemon.new) to make its form. It also generates an authenticity token, html tag ids (like <div id=pikachu >) and html tag names. Authenticity tokens prevents forgery on your site. The body of the form requires the attributes you would like to set and the field type for each attribute.
<%= f.text_field :name %>
<%= f.text_area :pokedex_description %>
There are many types of fields form_for supports, from password_fields to url_field.
The dynamic nature of form_for also means that it can be used to edit an object (one of your pokemon) by providing an object already saved in ActiveRecord (our pokedex).
pokemons_controller#edit
@pokemon = Pokemon.find(existing pokemon)
If the object already exists, form_for will add default values, button names, html class tags that reflect the existing object. More importantly, it will indicate that the method of the form is a patch instead of a post.
Lastly, the parameters passed to you will require strong parameters. If you receive a ActiveModel::ForbiddenAttribute exception, it only means you must tweek your .require(and).permit(statements).