0

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!

9
  • Can you put your Models. Commented Apr 29, 2011 at 15:29
  • This is the Contact model: pastie.org/1847692. This is the User model: pastie.org/1847695. Commented Apr 29, 2011 at 16:03
  • And what do you want at the end? ex: array[user.id, contact1.id, contact2.id ...] Commented Apr 29, 2011 at 18:52
  • The current output is like this: pastie.org/1848590. I want the contact ID to be sub array like the latest message is now. How can I do this? Commented Apr 29, 2011 at 20:50
  • Put me a exemple of output you want not the current Commented Apr 29, 2011 at 21:55

1 Answer 1

1

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

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.