简体   繁体   English

在创建之前检查Rails中是否存在记录

[英]Check if record exists in Rails before creating

I am trying to search my database before I enter the record, by doing this: 我想在输入记录之前搜索我的数据库,方法是这样做:

Product.update_or_create_by_name_and_date_and_applicationURL_and_server_and_addi_servers(app_name, app_date,url_app,server_name,addi_servers)

the problem is that I get an undefined method exception! 问题是我得到一个未定义的方法异常!

Is there another way to search for the same record before entering one? 是否有其他方法可以在输入之前搜索相同的记录?

You should use two steps: 您应该使用两个步骤:

#Suggestion 1
obj = Product.find_or_create_by_...


#Suggestion 2
obj = Product.find_or_initialize_by_...

obj.update_attributes hash_here

Rereading, your question, I can't really understand what do you want to update if you try to find an object with known attributes. 重读,你的问题,如果你试图找到一个具有已知属性的对象,我真的无法理解你想要更新什么。 Anyway, you would just have to adapt my answer a little if some fields are for identifying and some for update. 无论如何,如果某些字段用于识别而某些字段用于更新,则您只需稍微调整我的答案。

I would define a function in your model: something like 我会在你的模型中定义一个函数:类似于

Product.find_by_everything

where you write out all the parameters of the search, instead of using the the long naming method. 您写出搜索的所有参数,而不是使用长命名方法。

Then, if that returns nil, create the product. 然后,如果返回nil,则创建产品。 This doesn't seem to be a good use case of using the built in activerecord naming methods. 这似乎不是使用内置的activerecord命名方法的一个很好的用例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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