Objetivo
Se crearan algunas formas, primero usando HTML puro y despues se escalaran
usando metodos helper de rails.
Pasos:
1.Setup
2.Crear HTML Form
3.Crear #form_tag Form
4.Crear #form_for Form
5.Editando Users
6.Extra Credit
Step 1: Setup
1.1 Crea una app de rails con el modelo User y su controlador:
1.2 From the command line, create a new Rails app:
1.3 Create and Migrate User Model:
1.4 Add validations for presence:
class User < ActiveRecord::Base
validates :username, presence: true
validates :email, presence: true
validates :password, presence: true
end
1.5 Create routes for #new and #create actions:
1.6 Check to make sure routes were created:
1.7 Generate a UsersController:
1.8 Write empty methods for #newand #create:
1.9 Create new.html.erb file. Add boilerplate text to file.
1.10 From the command line, load development server using rails s.
Step 2: Build HTML Form
2.1 Build a form for creating a new user:
If you try to submit data now you will receive
an ActionController::InvalidAuthenticityToken error. Add authenticity token
as follows:
<form accept-charset="UTF-8" action="/users" method="post"> <input
type="hidden" name="authenticity_token" value="<%=
form_authenticity_token %>">
...
Now if you try to submit data, you will get a template is missing error.
That is okay. This means we've reached our #create action in the controller and
by default it looks for an app/views/users/create.html.erb file.
Instead, lets build the #create action to go elsewhere:
def create
@user = User.new(:username => params[:username], :email =>
params[:email], :password => params[:password])
if @user.save
redirect_to new_user_path
else
render :new
end
end
2.2 Create and implement a #user_params helper method:
class UsersController < ApplicationController
...
private
def user_params
params.require(:user).permit(:username, :email, :password)
end
2.3 Update html form to submit hash of user parameters: 2.4 Update #create
action with new helper method:
2.4 Update #create action with new helper method:
class UsersController < ApplicationController
...
def create
@user = User.new(user_params)
if @user.save
redirect_to new_user_path
else
render :new end
end
...
2.5 Finally, confirm you can submit data using the form:
Log output:
Started POST "/users" for 127.0.0.1 at 2014-05-05 17:56:21 -0400
Processing by UsersController#create as HTML
Parameters:
{"authenticity_token"=>"vapWanzKp+ZGIdvaE1HTcwS5ybQs/6pQJyuobJOcsmM=",
"user"=>{"username"=>"thor", "email"=>"[email protected]",
"password"=>"[FILTERED]"}}
(0.1ms) begin transaction
SQL (0.4ms) INSERT INTO "users" ("created_at", "email", "password",
"updated_at", "username") VALUES (?, ?, ?, ?, ?) [["created_at", Mon, 05
May 2014 21:56:21 UTC +00:00], ["email", "
[email protected]"], ["password",
"thor"], ["updated_at", Mon, 05 May 2014 21:56:21 UTC +00:00], ["username",
"thor"]]
(0.6ms) commit transaction
Redirected to http://localhost:3000/users/new Completed 302 Found in 14ms
(ActiveRecord: 2.4ms)
Step 3: Build #form_tag Form
3.1 Replace our html form with a #form_tag Form.
3.2 Modify#create method to once again accept normal top level User
attributes.
def create
@user = User.new(:username => params[:username], :email =>
params[:email], :password => params[:password]) #@user =
User.new(user_params)
...
end
3.3 Confirm you can submit data.
Step 4: Build #form_for Form
4.1 Modify your #new action in the controller to instantiate a blank User object
and store it in an instance variable called @user.
class UsersController < ApplicationController
def new
@user = User.new
end
...
4.2 Comment out #form_tag and build #form_for form:
4.3 Switch your controller's #create method to accept the nested :user hash
from params.
def create
#@user = User.new(:username => params[:username], :email =>
params[:email], :password => params[:password])
@user = User.new(user_params)
...
end
4.4 Confirm you can submit data using the newly created #form_for form:
Step 5: Editing Users
5.1 Update your routes and controller to handle editing an existing user. In
config/routes.rb :
...
In app/controllers/users_controller.rb :
class UsersController < ApplicationController
...
def edit
@user = User.find(params[:id])
end
def update
@user = User.find(params[:id])
if @user.update(user_params)
redirect_to edit_user_path(@user)
else
render :edit
end
end
5.2 Create app/views/users/edit.html.erb . Copy/paste your form from the New
view to Edit form:
"View source" on the form generated by #form_for in your Edit view.
You should see authentication token and other relevant hidden fields.
5.3 Confirm that you can submit data and that validations are working.
Step 6: Extra Credit
6.1 In app/views/users/new.html.erb and app/views/users/edit.html.erb ,
include error messages:
Now, when validations fail, errors should display: