0

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?

1
  • check out has_and_belongs_to_many and has_many :through Commented Dec 10, 2011 at 18:30

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.