当前位置 : 主页 > 编程语言 > ruby >

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

来源:互联网 收集:自由互联 发布时间:2021-06-23
tl; dr如何使用对象的键获取相应的值? 我很困惑为什么 Atag.where(标签:’品牌’)给了我一个我称之为对象的缺乏更好的术语:# ActiveRecord :: Relation [# Atag id:1,tag:“brand”,created_at:“
tl; dr如何使用对象的键获取相应的值?

我很困惑为什么

Atag.where(标签:’品牌’)给了我一个我称之为对象的缺乏更好的术语:#< 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(标记:’品牌’).id和Atag.where(标记:’品牌’)[:id]和Atag.where(标记:’品牌’)(:id)都抛出错误,而在这种情况下我只是想让整数1返回.

我似乎无法回顾,也没有用我的谷歌搜索技能(或缺乏)找到这个基本问题的简洁答案.

谢谢

使用以下查询获取tag =’brand’的ID:

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.
网友评论