我很困惑为什么
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 = 1Atag.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.classAtag.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.总结
以上是内存溢出为你收集整理的ruby-on-rails – 如何通过Ruby on Rails中的键访问对象的(ActiveRecord :: Relation)值?全部内容,希望文章能够帮你解决ruby-on-rails – 如何通过Ruby on Rails中的键访问对象的(ActiveRecord :: Relation)值?所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)