简体   繁体   中英

What is the best way to check if a record already exists in database in Rails?

I'm wondering what is the best way to check existence of an object before it's creation ?

I want to store search queries but it doesn't make sense to create a new one everytime if there's already one in database. I'd rather increment a counter to have stats about most common queries.

My biggest problem is how do I check if the object is already in base. I want to know if there is some magical function to check this without pulling out the whole table and checking if one of the objects equals the new one ?

Also, it really has to be on the form find_or_create( myObject ) and check if all the attributes are the same (and I have a lot on each query object) and ignore id of course.

So this means I can't use a find_or_create_by_region_id_and_departement_id_and_other_attr

Ah and I'm working with Rails 3.2.6 :)

Any idea how to do this ?

Edit to add table structure for search queries :

# == Schema Information
#
# Table name: search_queries
#
#  id                 :integer(4)      not null, primary key
#  region_id          :integer(4)
#  departement_id     :integer(4)
#  ville              :string(255)
#  environnement_id   :integer(4)
#  etoiles_min        :integer(4)
#  etoiles_max        :integer(4)
#  tente              :boolean(1)
#  caravane           :boolean(1)
#  campingcar         :boolean(1)
#  mobilhome          :boolean(1)
#  chalet             :boolean(1)
#  bungalow           :boolean(1)
#  yourte             :boolean(1)
#  roulotte           :boolean(1)
#  tipi               :boolean(1)
#  autres             :boolean(1)
#  wifi               :boolean(1)
#  restaurant         :boolean(1)
#  epicerie           :boolean(1)
#  depotpain          :boolean(1)
#  laverie            :boolean(1)
#  espace_aqua        :boolean(1)
#  club_enfant        :boolean(1)
#  multisport         :boolean(1)
#  loc_velo           :boolean(1)
#  acces_pmr          :boolean(1)
#  animaux            :boolean(1)
#  naturiste          :boolean(1)
#  l_campingqualite   :boolean(1)
#  l_qualitetourisme  :boolean(1)
#  l_tourismehandicap :boolean(1)
#  l_ecotourisme      :boolean(1)
#  l_normandiequalite :boolean(1)
#  l_ancv             :boolean(1)
#  created_at         :datetime        not null
#  updated_at         :datetime        not null
#

you can use first_or_create/first_or_initialize in order to create an object if there isn't one.

query = Query.where(...).first_or_initialize

#do something with the query (increment counter, store parameters)

query.save!

Rails luckily supports many sweet deals when it comes to validating existing records.

Like the other guys suggest There is an exists method wich you can apply to the data you want to check.

also validates_uniqueness_of is able to validate the record as a whole.

I personally favorite the find_or_create method which can even be chained with more parameters.

Have fun!

So as the Model.where method doesn't accept an object but only a hash and this hash mustn't contain an id field, what you need to use is this :

@query = SearchQuery.where( queryObject.instance_values["attributes"].except("id")      ).first_or_create

Where queryObject is the object you need to check the existence of

Thank you davidrac for your help :)

Although I'm kind of disapointed that Rails doesn't come with this built-in, I mean there are so many great things to a lot of tasks quicker than anywhere else and not this ?

The best way of doing this is to use exists? see this for more info.

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