Search code examples
ruby-on-railsruby-on-rails-4model-associationsrails-models

Implementing a model with two separate attributes with different names but with same type


I have a Model named Lock which keeps track of two Students who have locked a deal with each other. My Lock model has attributes buyer_id and seller_id which both are the id's of users from my User model. Is there a way to have attributes buyer and seller (for Lock model) that directly access their appropriate User?

For example, I would like to make a call like Lock.last.buyer.email instead of having to go through the user_id like User.find(Lock.last.buyer_id).email.

Also, will this difference in syntax make for better code? Or am I merely making a syntactical improvement for my own readability? Either way, I would like to know if its possible :)


Solution

  • Try these

    belongs_to :buyer, class_name: "User", foreign_key: :buyer_id
    belongs_to :seller, class_name: "User", foreign_key: :seller_id
    

    There is more info about belongs_to in the documentation.