user3133300
user3133300

Reputation: 627

(Ruby on Rails beginner) Referencing another model within a model

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

As you can see, I am using ActiveRecord and have the belongs_to association, so shouldn't accessing user attributes be easy?

Upvotes: 0

Views: 80

Answers (1)

Stewart
Stewart

Reputation: 3161

Yes it is.

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

You may also refer to your user from with in the model

class Prescription < ActiveRecord::Base

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

end

So really the question is how does Rails do this? The answer is meta programming. Meta programming is a complex topic within ruby. Put simply meta programming allows classes and objects to have methods added to them at run time. When your model loads it sees that you have a belongs to user defined. This will then in turn create the .user method in the above example. The method it's self will return the User model instance that is associated with the current Prescription object. Other active record methods do similar things such as has_many, has_one and has_and_belongs_to_many.

Upvotes: 2

Related Questions