Jonathan Clark
Jonathan Clark

Reputation: 20558

Rails 3. Getting multiple things from different tables

I am developing an API in Ruby on Rails 3 and in this API I got users and users can be friends. This is handled through Contacts. When a user "asks" for all his or her contacts I create an array that takes the Ids of each user and get the User object for them so that I can get the real name of the contact and not just the contact ID.

This works fine, but I also need the ID of the contact so that I can for example delete contacts in the iPhone app that I am developing. How can I do this? How can the below code be modify to get the contact ID for each user and the user object?

http://pastie.org/1847350

UPDATE

The current JSON output is pastie.org/1848590. I want the contact IDs to be a sub array of the main User object array. Like the latest message is now.

Thankful for all input!

Upvotes: 0

Views: 149

Answers (1)

Ali Hassan Mirza
Ali Hassan Mirza

Reputation: 592

Contact is also the user, I think you just need to create a user model and add a self association with class_name: "contact" and this relation will b the one to many relationship one user has_many contacts.

 has_many :contacts, class: "contacts", foreign_key: "contact_id"      

Here is cast for this

http://railscasts.com/episodes/163-self-referential-association

after the association you just need to find that user and then just

@users.collect{|user| user.contacts }

returns you the list of the contacts I think that might help you.

Cheers

Upvotes: 1

Related Questions