当我尝试访问从DB获取的对象的字段时,NoMethodError

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

  • 身份certificate
  • 2.内容
  • 3. created_at
  • 4. user_id
  • 5. original_tweet_id

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

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

我在尝试对查询产生的此对象执行@original.id时遇到错误:

 @original => #<ActiveRecord::Relation [#]> 

从我的ruby知识中得到的东西真的很缺失……帮助!

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

而不是

 @tweet = Tweet.where(id: 64) 

你要

 @tweet = Tweet.find(64) 

因为你正在使用id

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

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

 @original = Tweet.find_by_id(64) 

要么

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

这样做,你需要先添加

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

在您的情况下,它返回Active Record Relation对象的集合

所以具体记录

@original.first.id给你64

要么

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