问题描述
我发出这样的准确检索0或1的记录以下查询:
车= Car.where(VIN:1234567890abcdefg)
什么是返回当然是长度为1所以我最终加入。首先
在查询末尾的车的列表:
车= Car.where(VIN:1234567890abcdefg)第一。
好像应该是Rails的一个更好的办法。是否像 .onlyOne
存在,这将只返回一个车
,如果有超过1抛出一个异常?
车= Car.where(VIN:1234567890abcdefg)。onlyOne
或
车= Car.onlyOne(VIN:1234567890abcdefg)
轨道4
您想要 find_by(VIN:123)
,您可以通过 find_by
的任何字段/值的哈希名称查找。
如:
Car.find_by(VIN:'123')
如果没车与VIN发现这将返回零,或单一的汽车匹配的VIN值。如果添加一个感叹号(即 find_by!
),如果没有车的VIN发现它会引发异常。
如果你想提高一个错误,如果超过一个发现,那是后话,你必须写自己。如果你不应该进入一个以上的汽车都有相同的VIN,这样做将是对汽车模型唯一性验证的最好方法,案件如:
类汽车<的ActiveRecord :: Base的
validates_uniqueness_of:VIN#或验证:VIN,独特的:真正的
结束
的Rails 3
您想要 find_by_vin
(你可以替换 VIN
与您的任何属性的名称。
如:
Car.find_by_vin('123')
如果没车与VIN发现这将返回零,或单一的汽车与VIN值。如果添加一个感叹号(即 find_by_vin!
),如果没有车的VIN发现它会引发异常。
有关详细信息:http://guides.rubyonrails.org/active_record_querying.html#retrieving-objects-from-the-database
I issue queries like the following that retrieve exactly 0 or 1 records:
car = Car.where(vin: '1234567890abcdefg')
What's returned is of course a list of cars of length 1. So I end up adding .first
at the end of the query:
car = Car.where(vin: '1234567890abcdefg').first
Seems like there should be a better way in Rails. Does something like .onlyOne
exist which would return just a single Car
and throw an exception if there was more than 1?
car = Car.where(vin: '1234567890abcdefg').onlyOne
or
car = Car.onlyOne(vin: '1234567890abcdefg')
Rails 4
You want find_by(vin: 123)
, and you can pass find_by
a hash of any field/value names to find by.
eg.
Car.find_by(vin: '123')
This will return nil if no car with that vin is found, or a single car matching that vin value. If you add a bang (ie. find_by!
) it will raise an exception if no car with that vin is found.
If you want to raise an error if more than one is found, that is something you'll have to write for yourself. If you should never get into the case where more than one car has the same vin, the best way to do this would be with a uniqueness validation on the Car model, eg.
class Car < ActiveRecord::Base
validates_uniqueness_of :vin # or validates :vin, unique: true
end
Rails 3
You want find_by_vin
(and you can replace vin
with the name of any of your attributes.
eg.
Car.find_by_vin('123')
This will return nil if no car with that vin is found, or a single car with that vin value. If you add a bang (ie. find_by_vin!
) it will raise an exception if no car with that vin is found.
For more information: http://guides.rubyonrails.org/active_record_querying.html#retrieving-objects-from-the-database
这篇关于检索单个记录从一个ActiveRecord / Rails的查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!