如何在Ruby on Rails中通过键访问对象的(ActiveRecord :: Relation)值?

Las*_*ser 5 ruby activerecord ruby-on-rails ruby-on-rails-4

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返回。

我似乎无法用红宝石浏览,也无法用我的Google搜索技能(或缺乏)找到这个基本问题的简洁答案。

谢谢

Aja*_*jay 5

通过以下查询获取标签='brand'的ID:

Atag.find_by(tag:'brand').id 
Run Code Online (Sandbox Code Playgroud)

检查以下变化:

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. 
Run Code Online (Sandbox Code Playgroud)

更好的选择:

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.
Run Code Online (Sandbox Code Playgroud)

使用动态查找器获得相同的味道。

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. 
Run Code Online (Sandbox Code Playgroud)


cki*_*b16 5

来自Odin 项目的优秀文档。

需要注意的关键是#find返回实际记录,而#where返回一个ActiveRecord::Relation基本上就像一个数组。

因此,如果您使用#where查找单个记录,您仍然需要记住进入该“数组”并获取第一条记录,例如User.where(:email => "foo@bar.com")[0]User.where(:email => "foo@bar.com").first.

这让我一直...