What is build_resource and resource in Devise Ruby on Rails?

Viewed 5557

Where can I change the validation to save, using the Devise gem? I found this form:

def create
  build_resource(sign_up_params)
  if resource.valid?
    super
  else
    render :new
  end
end

But what I find is similar to this:

def create
  @user = User.new(user_params)

  respond_to do |format|
    if @user.save
      format.html { redirect_to @user, notice: 'User was successfully created.' }
    format.json { render :show, status: :created, location: @user }
    else
      format.html { render :new }
      format.json { render json: @user.errors, status: :unprocessable_entity }
    end
  end
end
1 Answers

Devise is made to work with any model, it is not mandatory to be User. A very common example is to have User and AdminUser.

If Devise was hardcoded to as you showed (User.new), it means that it'd never work for a different model nor it would allow you to have more than a model signing in into your webapp. Knowing that, the resource represents the model that you have added devise to, and that's signing in. In your case:

 build_resource(sign_up_params) # will be the similar to user = User.new(sign_up_params)
 resource # will be an instance of User
 resource.valid? # will be the name as user.valid?

Since it's using resource.valid?, you just need to implement the validations within the model User or AdminUser without changing any code in Devise.

Related