我想知道在創建對象之前檢查對象的存在的最佳方法是什麼?檢查Rails中的數據庫中是否存在記錄的最佳方法是什麼?
我想存儲搜索查詢,但如果數據庫中已經存在搜索查詢,那麼每次創建一個新搜索查詢都沒有意義。我寧願增加一個計數器來獲得關於大多數常見查詢的統計信息。
我最大的問題是如何檢查對象是否已經在基地。我想知道是否有一些神奇的功能來檢查這一點,而不用拉出整個表格並檢查一個對象是否等於新對象?
此外,它確實必須在find_or_create(myObject)
的形式,並檢查是否所有的屬性都是相同的(我對每個查詢對象有很多),當然忽略id
。
因此,這意味着我不能使用find_or_create_by_region_id_and_departement_id_and_other_attr
啊,我使用Rails 3.2.6 :)
任何想法工作如何做到這一點?
編輯添加表結構爲搜索查詢:
# == 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
#
那麼這個問題是當我做Query.where(queryObject),它說我有一個TypeError:無法訪問查詢,我完全不知道這是什麼意思 – 2012-08-02 15:27:18
你能分享相關的代碼嗎? – davidrac 2012-08-02 15:29:14
'@search_query = SearchQuery.where(params [:search_query])。first_or_create' – 2012-08-03 07:31:45