On 09/07/14 21:37, Nick Sabalausky wrote:

What I've started doing, and absolutely love so far, is to write my
forms purely in the HTML template (with a little bit a custom
tags/attributes), then use Adam's HTML DOM to read that HTML form and
generate all the backend form-handing *from* the HTML form, including
all the appropriate per-field "validation failed".

I'm finding this works a lot better than defining forms in the backend
code and then trying to generate the HTML I want from that.

To me that sounds a bit backwards. I'm not exactly sure what you mean by "backend form-handling" but in Rails all ActiveRecord classes can take a hash (associative array) in the constructor. The keys will match the fields (columns) on the class and the constructor will automatically assign all fields with the given values. This is called mass-assignment.

The view uses appropriate names for the form fields, scoped in the same name as the model, like this:

<input type="text" name="person[name]" />

So the only thing you need to do in the controller is something like this:

def create
  user = User.new(params[:user])
  user.save
end

In the view you use a form builder:

= simple_form_for @user do |f| do
  = f.input :name
  = f.input :admin
  = f.association :role
  = f.button :submit

Here I'm using a plugin called SimpleForm, it will automatically render the correct input form type based on the column type in the database. "name" will be render as a text input. "admin" will be render as a checkbox (since it's a boolean). It will also add labels and similar things. It can also generate all necessary code to be compatible with Bootstrap.

"f.association :role" is quite interesting. This expects there to be an association to the Role model in the User model. It will render a select tag populated with all the rows from the Role table.

The validation is handled in the model, where it belongs, when "save" is called in the controller. There's also a plugin that will automatically add JavaScript validations. It has duplicated the standard Rails validators in JavaScript. It will inspect the model, choose the correct validator and add it when rendering the view.

--
/Jacob Carlborg

Reply via email to