tl; dr如何使用对象的键获取相应的值?
我很困惑为什么
Atag.where(tag:'brand')
为我提供了一个因缺乏更好条款而称之为对象的内容:#<ActiveRecord::Relation [#<Atag id: 1, tag: "brand", created_at: "2015-01-31 04:29:20", updated_at: "2015-01-31 04:29:20">]>
但是我很难获得密钥的相应值:id。
Atag.where(tag:'brand').id
和Atag.where(tag:'brand')[:id]
以及Atag.where(tag:'brand')(:id)
都会抛出错误,而在这种情况下,我只是尝试返回整数1。
我似乎无法回顾,也没有用我的谷歌搜索技能(或缺乏)找到这个基本问题的简洁答案。
由于
答案 0 :(得分:5)
获取您的代码的ID =&#39;品牌&#39;以下查询:
Atag.find_by(tag:'brand').id
检查以下变化:
Atag.find(1)
#gives you the object with the Atag id = 1
Atag.find(100) #let's say this record does not exist then you will
get ActiveRecord::RecordNotFound exception.
更好的选择:
Atag.where(id: 1)
#this returns you a relation and it's true you are trying to access
only a single object.
Hence, you just need to modify it to :
Atag.where(id: 1).first
#Above one will give you an object of Atag not an association result.
# to verfiy you can execute, Atag.where(id: 1).first.class
Atag.where(id: 999).first
# In this case if there is no record found with id = 999, then it'll
return nil which can be easily handled than an exception found
while using find method.
使用动态查找器获得相同的味道。
Atag.find_by(id: 1) #gives the Atag with id 1
Atag.find_by_id(1). # same as above.
Atag.find_by(id: 999) #if not found then simply returns nil.
Atag.find_by(name: 'ruby') #return Atag object with name: 'ruby'
Atag.find_by_name('ruby') #same as above.
答案 1 :(得分:2)
来自Odin Project的精彩文档。
需要注意的关键是
#find
返回实际记录,而#where
返回ActiveRecord::Relation
,它基本上就像一个数组。因此,如果您使用
#where
查找单个记录,则仍需要记住进入该“数组”并抓住第一条记录,例如User.where(:email => "foo@bar.com")[0]
或User.where(:email => "foo@bar.com").first.
这让我一直都在......
答案 2 :(得分:1)
Atag.where(tag:'brand').first
获取第一个结果,使用Atag.where(tag:'brand').to_a
获取所有匹配结果的数组。
答案 3 :(得分:0)
的数组成员一样访问它
where
返回 ActiveRecord :: Relation 的实例,可以将其视为数组,并将记录作为其成员。即使结果是单一的,也应该像使用单个元素
Atag.where(tag: 'brand')
返回结果数组并访问id
我们应该首先从数组中获取记录,即
Atag.where(tag: 'brand')[0].id
为了获得所有匹配记录的id
,我们需要将pluck与where
一起使用。 pluck
返回一个被拔除的属性数组。
Atag.where(tag: 'brand').pluck(:id)
这将从id
返回的集合中返回where
数组。
find_by
方法查找匹配某些条件的第一条记录。由于find_by
会返回记录(不是数组),我们可以这样做:
Atag.find_by(tag: 'brand').id
PS:没人提到pluck
这就是我写这个答案的原因。希望它有所帮助。