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">]>
但是我在访问 key 的相应值时遇到了基本困难:id。
Atag.where(tag:'brand').idAtag.where(tag:'brand')[:id]Atag.where(tag:'brand')(:id) 都会抛出错误,而在这种情况下,我只是想返回整数 1。

我似乎无法用我的谷歌搜索技巧(或缺乏)找到这个基本问题的简洁答案。

谢谢

最佳答案

使用以下查询获取标签 = '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.

使用动态查找器获得相同的 flavor 。
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.

关于ruby-on-rails - 如何在 Ruby on Rails 中通过键访问对象的 (ActiveRecord::Relation) 值?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/28248345/

10-11 01:54
查看更多