简体   繁体   中英

exists? Ruby Postgresql Active Record Validation with multiple conditions

I Want, compare if this two params exists on database on same register id.

Example:

Data.all return this.

phone_number | adress
12345678     | route 66

On check if below return true for all params.

My If with active record :

 if Data.exists?(phone_number: "#{params["phone_number"]}", adress: "#{params["adress"]}")
   puts "true, it's registered"

 else
  puts "false not, registered."
  Data.create!(phone_number: "#{params["phone_number"]}", adress: "#{params["adress"]}")

 end

if above return false for new select from two params

example:

Data.all return this.

phone_number | adress
95654152   | route 67

Create register a new register with params, and not duplicate.

Can you help me? as I wrote it, it is validating only 1 condition, not the 2 parameters.

Use active record #find_or_create_by . you can check the documentation here https://apidock.com/rails/v4.0.2/ActiveRecord/Relation/find_or_create_by

Data.find_or_create_by(phone_number: params[:phone_number], adress: params[:adress])

A simple solution might be to use ActiveRecord#find_or_create_by method which returns an existing record or generate a new one if it does not exist yet:

Data.find_or_create_by(phone_number: params["phone_number"], adress: params["adress"])

Note there is no need to use string interpolation ( "#{ ... }" ) in this case. Or even shorter:

Data.find_or_create_by(params.permit(:phone_number, :adress))

But when you really need to make sure that there will never be to identical records in the database then you should ensure that in the model and the database too.

I suggest adding an uniqueness validation to the model

# in app/models/data.rb
validates :phone_number, uniqueness: { scope: :adress, case_sensitive: false }

and a unique index to the database

add_index :datas, [:phone_number, :adress], unique: true

The combination of validation and the index ensures that you can't end up with duplicates in the database even if you forget using find_or_create in another controller or import data into the database through another channel.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM