NoMethodError 当我尝试访问从数据库中获取的对象的字段时 [英] NoMethodError when I try to acces a field of an object taken from the DB

查看:32
本文介绍了NoMethodError 当我尝试访问从数据库中获取的对象的字段时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 假设我有一个名为 Tweet 的模型,其中包含以下字段

  Let's say that I have a model called Tweet with the following fields

  • 1.id
  • 2.内容
  • 3.created_at
  • 4.用户 ID
  • 5.original_tweet_id

 现在假设我使用以下查询 @tweet = Tweet.where(id: 64) 查询此模型,此查询返回一个没有字段 nil 的对象.

  Now let's say I query this model with the following query @tweet = Tweet.where(id: 64) and this query returns an object with no fields nil.

 为什么我不能通过执行 @tweet.id 或 @tweet.content 来访问字段?我得到 NoMethodError NoMethodError: undefined methodid' for #Tweet::ActiveRecord_Relation:0x00000006e6ce80

  Why can't I acces a field by doing @tweet.id or @tweet.content ? I get NoMethodError NoMethodError: undefined methodid' for #Tweet::ActiveRecord_Relation:0x00000006e6ce80

 我尝试在查询结果的这个对象上执行 @original.id 时出错:

  I got the error trying to execute @original.id on this object that resulted from the query :

@original
 => #<ActiveRecord::Relation [#<Tweet id: 64, content: "Unde et nisi blanditiis vel occaecati soluta praes...", user_id: 4, created_at: "2014-12-22 08:56:46", updated_at: "2014-12-22 08:56:46", picture: nil, group: nil, original_tweet_id: nil>]>

 我的 ruby​​ 知识中的某些东西真的缺失了......帮助!!!

  Something from my ruby knowledge is really missing...help!!!

推荐答案

这是因为 where 返回的是集合而不是单个对象

It's because where returns a collection not a single object

所以代替

@tweet = Tweet.where(id: 64)

你想要

@tweet = Tweet.find(64)

因为您使用的是 id

这篇关于NoMethodError 当我尝试访问从数据库中获取的对象的字段时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆