我想知道在对象创建之前检查对象存在的最佳方法是什么?
我想存储搜索查询,但如果数据库中已存在一个新搜索查询,那么每次创建新搜索查询都没有意义。我宁愿增加一个计数器,以获得有关大多数常见查询的统计信息。
我最大的问题是如何检查对象是否已经存在。我想知道是否有一些神奇的功能来检查这个,而不是拉出整个表并检查其中一个对象是否等于新的?
此外,它必须位于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
#
答案 0 :(得分:3)
如果没有对象,您可以使用first_or_create/first_or_initialize
来创建对象。
query = Query.where(...).first_or_initialize
#do something with the query (increment counter, store parameters)
query.save!
答案 1 :(得分:0)
Rails在验证现有记录方面幸运地支持许多甜蜜的交易。
像其他人一样建议有一种存在方法可以应用于你想要检查的数据。
同样validates_uniqueness_of能够整体验证记录。
我个人最喜欢find_or_create方法,它甚至可以用更多参数链接。
玩得开心!
答案 2 :(得分:0)
因为Model.where
方法不接受对象而只接受散列,并且此散列不能包含id字段,所以您需要使用的是:
@query = SearchQuery.where( queryObject.instance_values["attributes"].except("id") ).first_or_create
其中queryObject是您需要检查
存在的对象感谢davidrac的帮助:)
虽然我对Rails没有附带这个内置功能感到失望,但我的意思是,有很多很棒的东西可以比其他任何地方更快地完成很多任务而不是这个?
答案 3 :(得分:0)
执行此操作的最佳方法是使用exists?
有关详细信息,请参阅this。