对于ActiveRecord的::关系未定义的方法关系、未定义、方法、ActiveRecord

2023-09-09 22:05:36 作者:过街小熊

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在这条线
 
Rails Active Record Associations 笔记 一

解决方案

那么,你得到回的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.