2011-05-14 121 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 

我知道你已經接受一個答案,但認爲這將有助於進一步減少錯誤/混淆。

相關問題