In the output, I will post how to write validation in Rails.
Validation is the verification that the data is correct.
First in the model
user.rb
class User < ApplicationRecord
validates :nickname, presence: true
:nickname #Column name
presence: true #Not empty
Then the controller
user_controller.rb
class UsersController < ApplicationController
def new
@user = User.new
end
def create
@user = User.new(user_params)
if
@user.valid? #here! !! here! !! !!
@user.save
redirect_to root_path
else
render 'new'
end
end
private
def user_params
params.require(:item).permit(
:nickname
end
end
Validation is executed by the valid? method. Returns true if validation is successful.
As a flow, check with validation whether the value is entered when saving what was generated by the new action with the create action. If you use the if statement, save it as @ user.save. If empty, alert with render'new'. , ,
ruby:user.html.haml
= f.text_field :nickname, class: "nickname"
.error-messages
= @user.errors.full_messages_for(:nickname)[0]
In the view, write the nickname to save and the error message display = @ user.errors.full_messages_for (: nickname) [0] to complete.
Recommended Posts