Kamilski81
Kamilski81

Reputation: 15107

How do I use inheritance with ActiveRecord models in rails?

I currently have a User (has_many: address_book_users) and an AddressBookuser (columns: user_id, user_id_inserted)

Currently, when I call user.address_book_users, I get back an array on ints, like [3, 4, 5] which correspond to users which are in my address book.

When iterating through this array I have to do a:

for uid in user.address_book_users 
  user = User.find(uid)

to get access to each user.

What would be a better way to do this, or should I remodel my relationship somehow to where Rails knows that column user_id_inserted refers to an ID of a user?

Upvotes: 0

Views: 40

Answers (1)

dombesz
dombesz

Reputation: 7899

First you have to name the AddressBookUser model's user_id_inserted like, contact.

class AddressBookUser < ActiveRecord::Base
  belongs_to :contact, :foreign_key=>'user_id_inserted', :class_name=>'User'
end

Then define a has_many :through relation.

class User < ActiveRecord::Base
  has_many :contacts, :through=> :address_book_users
end

Then call user.contacts and you should receive all the users on addressbook.

Upvotes: 1

Related Questions