Home > database >  How can I validate the object's attribute and values exist?
How can I validate the object's attribute and values exist?

Time:10-04

My goal is to validate my form and making sure all fields filled out in my form exists and not blank. if ALL these condition's attributes first_name, last_name, date_of_birth exists AND values are not blank it can search the database; otherwise, it just return to the search page with an error telling the user that all fields need to be filled out. Im doing this validation for my backend.

I currently having this object received from filling out a form in my view:

pry(#<RegistrantsController>)> @q.conditions
=> [Condition <attributes: ["first_name"], predicate: matches, values: ["John"]>, Condition <attributes: ["last_name"], predicate: matches, values: ["Smith"]>]

As you see I haven't filled out the date_of_birth in my form that's why it is not in this array but basically that's why I want to validate this.

how can I loop through and implement this condition?

CodePudding user response:

Use the validations provided by ActiveModel just like you would in normal CRUD actions:

class SearchForm
  include ActiveModel::Model
  include ActiveModel::Attributes
  attribute :first_name, type: :string
  attribute :last_name,  type: :string
  attribute :date_of_birth, type: :date
  validates :first_name, :last_name, 
            :date_of_birth, presence: true
end
class SomeController

  def search
    @search_form = SearchForm.new(search_params)
    if @search_form.valid?
      # do something
    else
      flash.now[:error] = "Oh noes..."
      render :some_kind_of_view
    end
  end


  private
  
  def search_params
    params.require(:q)
          .permit(:first_name, :last_name, :date_of_birth)
  end
end

CodePudding user response:

In the model is where you should do your validations.

class Model < ApplicationRecord
    validates :first_name, :last_name, presence: true

end

then is the controller for that model you should be able to create a conditional:

def create
        @user = User.new(user_params)
        if @user.save
          //....
        else 
          render json: @user.errors.full_messages, status: 422
        end
end

def user_params
    params.require(:user).permit(:first_name, :last_name, :date_of_birth)
end
  • Related