如何在 Rails 3 中将多个属性传递给 find_or_create_by? [英] How can I pass multiple attributes to find_or_create_by in Rails 3?

查看:20
本文介绍了如何在 Rails 3 中将多个属性传递给 find_or_create_by?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 find_or_create_by,但此语句不起作用.它不会查找"或创建"其他属性.

I want to use find_or_create_by, but this statement does NOT work. It does not "find" or "create" with the other attributes.

productproperty = ProductProperty.find_or_create_by_product_id(:product_id => product.id, :property_id => property.id, :value => d[descname])

关于在 Rails 3 中使用动态查找器的信息似乎很少,或者没有.将这些和"组合在一起会给我一个未知的方法错误.

There seems to be very little, or no, information on the use of dynamic finders in Rails 3. "and"-ing these together gives me a an unknown method error.

更新:

最初我无法使以下内容起作用.请假设我不是白痴,产品"是产品 AR 模型的一个实例.

Originally I couldn't get the following to work. Please assume I'm not an idiot and "product" is an instance of Product AR model.

product.product_properties.find_or_create_by_property_id_and_value(:property_id => 1, :value => "X")

错误方法是:

no such keys: property_id, value

我想不通.直到今天早上,我才找到了传递这样的值的参考:

I couldn't figure that out. Only this morning did I find the reference to passing the values like this instead:

product.product_properties.find_or_create_by_property_id_and_value(1, "X")

瞧,它工作正常.我本来希望哈希能在相同的情况下工作,但我猜不是.

And voilá, it works fine. I would have expected a hash to work in the same situation but I guess not.

所以我想如果你错过了互联网上的某些东西,你会得到反对票吗?

So I guess you get a down vote if you miss something on the internet?

推荐答案

如果要按多个属性进行搜索,可以使用和"来附加它们.例如:

If you want to search by multiple attributes, you can use "and" to append them. For example:

productproperty = ProductProperty.find_or_create_by_product_id_and_property_id_and_value(:product_id => product.id, :property_id => property.id, :value => d[descname])

有一个小问题需要注意.它将始终返回您指定的对象,即使该对象由于验证错误而无法保存.因此,请务必检查返回的对象是否具有 id(或 is_valid?).不要假设它在数据库中.

There is one minor catch to be aware of. It will always return the object you've specified, even if that object can't be saved due to validation errors. So make sure you check to see if the returned object has an id (or is_valid?). Don't assume its in the database.

或者,如果无法保存对象,您可以使用该方法的bang"版本来引发错误:

Alternatively, you can use the 'bang' version of the method to raise an error if the object cannot be saved:

http://guides.rubyonrails.org/active_record_querying.html#find-or-通过爆炸创建

这适用于 Rails 3.

This applies to Rails 3.

这篇关于如何在 Rails 3 中将多个属性传递给 find_or_create_by?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆