ActiveRecord::Relation 的未定义方法 [英] undefined method for ActiveRecord::Relation

查看:20
本文介绍了ActiveRecord::Relation 的未定义方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

用户模型

class User < ActiveRecord::Base
  has_many :medicalhistory 
end

医学历史模型

class Medicalhistory < ActiveRecord::Base
  belongs_to :user #foreign key -> user_id
  accepts_nested_attributes_for :user
end

错误

undefined method `lastname' for #<ActiveRecord::Relation:0xb6ad89d0>


#this works
@medicalhistory = Medicalhistory.find(current_user.id) 
print   "
" + @medicalhistory.lastname

#this doesn't!
@medicalhistory = Medicalhistory.where("user_id = ?", current_user.id)
print   "
" + @medicalhistory.lastname #error on this line

推荐答案

好吧,您正在返回 ActiveRecord::Relation 的对象,而不是您的模型实例,因此错误,因为没有ActiveRecord::Relation 中名为 lastname 的方法.

Well, you are getting back an object of ActiveRecord::Relation, not your model instance, thus the error since there is no method called lastname in ActiveRecord::Relation.

执行@medicalhistory.first.lastname 有效,因为@medicalhistory.first 正在返回由where.

Doing @medicalhistory.first.lastname works because @medicalhistory.first is returning the first instance of the model that was found by the where.

此外,您可以打印出@medicalhistory.class 的工作代码和错误"代码,看看它们有何不同.

Also, you can print out @medicalhistory.class for both the working and "erroring" code and see how they are different.

这篇关于ActiveRecord::Relation 的未定义方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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