NoMethodError当我试图访问从数据库中获取的对象的字段时



nbsp;假设我有一个名为Tweet的模型,具有以下字段

  • 1.id
  • 2.内容
  • 3.创建日期
  • 4.user_id
  • 5.original_tweet_id

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

;为什么我不能通过@tweet.id或@tweet.content访问字段?我得到#Tweet::ActiveRecord_Relation:0x00000006e6ce80 的NoMethodError NoMethodError: undefined method id

;我在尝试对此对象执行@original.id时遇到错误,该错误是由以下查询引起的:

@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>]>

;我的红宝石知识真的缺失了。。。帮助

@original不是Tweet实例,而是ActiveRecord::Relation

如果你想直接访问你的推文id,你应该像这个一样定义@original

@original = Tweet.find_by_id(64)

@original = Tweet.where(id: 64).first

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

所以不是

@tweet = Tweet.where(id: 64)

你想要

@tweet = Tweet.find(64)

因为您使用的是id

相反,您需要添加first

@tweet = Tweet.where(id: 64).first

在您的情况下,它返回活动记录关系的对象集合

所以对于特定的记录

@original.first.id为您提供64

  @tweet = Tweet.find(64)
  @tweet.id #64
  @tweet.content # "Unde et nisi blanditiis vel occaecati soluta praes..."

最新更新