2015-12-03 139 views
0
class Prescription < ActiveRecord::Base 
belongs_to :user 

validates :time, presence:true 
validates :user_id, presence:true 

#I want to access an attribute from the user model, but this does not work: 
num = self.user.mobilephone 

END 

正如你所看到的,我使用的ActiveRecord並有belongs_to協會,所以不應該訪問的用戶屬性很容易內引用另外一個模型?(Ruby on Rails的初學者)的模型

+0

@ user313330用您的問題添加更多細節。 – 2015-12-03 02:35:09

回答

2

是的。

p = Prescription.find(1) # Assuming you have a record with an ID of 1 
p.user.first_name #=> "Fred" Assuming you have a field in user called first_name 

您還可以參考你的用戶從與模型

class Prescription < ActiveRecord::Base 

    def user_full_name 
    "#{self.user.first_name} #{self.user.last_name}" 
    end 

end 

所以,真正的問題是如何Rails的做到這一點?答案是元編程。元編程是ruby中的一個複雜主題。簡單地說,元編程允許類和對象在運行時添加方法。當你的模型加載它看到你有一個屬於用戶定義。這將在上面的示例中依次創建.user方法。它自己的方法將返回與當前處方對象關聯的用戶模型實例。其他活動記錄方法也會執行類似的操作,例如has_many,has_one和has_and_belongs_to_many。

+0

我嘗試訪問使用self.user.first_name但它沒有工作。它說「用戶」部分是未定義的。 – user3133300

+0

用戶是否在數據庫中設置?您可以發佈您使用的代碼以及您獲得的錯誤消息。 – Stewart

+0

我更新了我的代碼。我得到的錯誤是「TypeError:類用戶的超類不匹配」 – user3133300