对于ActiveRecord的::关系未定义的方法 [英] undefined method for ActiveRecord::Relation

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

问题描述

User模型

 类用户的LT;的ActiveRecord :: Base的
  的has_many:medicalhistory
结束
 

Mdedicalhistory模型

 类Medicalhistory<的ActiveRecord :: Base的
  belongs_to的:用户#foreign键 - >用户帐号
  用户:accepts_nested_attributes_for
结束
 

错误

 未定义的方法'姓'为#<的ActiveRecord ::关联:0xb6ad89d0>


#这个作品
@medicalhistory = Medicalhistory.find(current_user.id)
打印\ N+ @ medicalhistory.lastname

#这个不!
@medicalhistory = Medicalhistory.where(user_ID的=?,current_user.id)
打印\ N+ @ medicalhistory.lastname #ERROR在这条线
 

解决方案

那么,你得到回的ActiveRecord ::关联的对象,而不是你的模型实例,从而的错误,因为有的ActiveRecord ::关联

没有方法称为

@ medicalhistory.first.lastname 的作品,因为 @ medicalhistory.first 正在恢复模型的第一个实例被发现的其中,

此外,您还可以打印出 @ medicalhistory.class 为工作和示数code,看看他们是如何的不同。

User model

class User < ActiveRecord::Base
  has_many :medicalhistory 
end

Mdedicalhistory model

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

Error

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


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

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

解决方案

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.

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

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

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

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