2011-05-14 113 views
22

用户模型ActiveRecord的未定义的方法::关系

class User < ActiveRecord::Base 
    has_many :medicalhistory 
end 

Mdedicalhistory模型

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 "\n" + @medicalhistory.lastname 

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

什么是错误信息? – 2011-05-14 21:33:33

+0

'@ medicalhistory.first.lastname'是否有效? – Zabba 2011-05-14 21:38:17

+0

:(是的,这是....洞察? – Omnipresent 2011-05-14 21:39:11

回答

39

那么,你得到回ActiveRecord::Relation的对象,而不是你的模型实例,因此没有m的错误在ActiveRecord::Relation中称为lastname的方法。

在做@medicalhistory.first.lastname工作,因为@medicalhistory.first正在返回where找到的模型的第一个实例。

此外,您可以打印出@medicalhistory.class的工作和“错误”代码,并查看它们的不同之处。

+1

谢谢,在查看API时我错过了第一种方法。 – Smar 2013-04-05 08:19:34

5

其他有一点需要注意,:medicalhistory应该是复数,因为它是一个has_many关系

所以,你的代码:

class User < ActiveRecord::Base 
    has_many :medicalhistory 
end 

应该写成:

class User < ActiveRecord::Base 
    has_many :medicalhistories 
end 

从Rails的文档(found here

当声明has_many 关联时,另一个模型的名称被复数化。

这是因为rails自动从关联名称中推断出类名。

如果用户只had_onemedicalhistory为你写了这将是单数:

class User < ActiveRecord::Base 
    has_one :medicalhistory 
end 

我知道你已经接受一个答案,但认为这将有助于进一步减少错误/混淆。

相关问题