I'll write about what to do if you want a particular validation to work only on a particular controller.
For example, when registering user information, consider when you want to register information step by step.
Users table
column | type |
---|---|
name | string |
string | |
password | string |
address | string |
image | string |
Page 1: name, email, password 2nd page: address, image
Consider the process of saving name, email, and password, and then saving adress and image.
If you want to make all columns mandatory, just write presence: true
in the model and you will get an error when registering the first page. (Because the address and image are empty)
What should I do if I want to use different validations on the first and second pages?
You can use with_options
for each action.
The image is like giving the model a name for the validation group as with_options on: ~ do
and checking the validation using thevalid? (Name)
method on the controller.
The specific writing method is as follows. (Please note that some parts are written with a slight break.)
model
with_options on: :step1 do
validates :name, presence: true
validates :email, uniqueness: true
validates :password, presence: true, length: { minimum: 8 }
validates :password, confirmation: true
end
with_options on: :step2 do
validates :address, presence: true
validates :image, uniqueness: true
end
step1 controller
def create
@user = User.new(user_params)
if @user.valid?(:step1) && @user.save
return redirect_to step2_path
end
render :new
end
step2 controller
def update
@user = User.find(params[:id])
if @user.valid?(:step2) && @user.update(user_params)
return redirect_to user_path
end
render :edit
end
If you want to apply all validations at the same time, you need to write as valid? (: Step1) && valid? (: Step2)
, which is a little troublesome ...
(I thought that all with_options would be used just by valid ?, but it didn't work)
By the way, if you want to use create and update properly, please refer to the article here. (Although there is a part that overlaps with this post ...)
Recommended Posts