views:

740

answers:

1

I'm working on a Rails app that will serve as an authentication system for other Rails apps through Rails's ActiveResource functionality.

The authentication app has an ActiveRecord model called User. The client app has an ActiveResource model called User. I know that in the client app I can do stuff like user.save and it will perform a PUT operation using XML over HTTP.

But what if I want to put into my client app's User model has_many :contacts or something like that (contacts being an ActiveRecord model in the client app)? Then I'd want to do stuff like get all the Contacts that belong to some User.

Is that possible?

(I noticed that a similar question was asked, but there weren't many responses.)

+2  A: 

Short answer: no. The classes involved in has_many, belongs_to, has_and_belongs_to_many live in ActiveRecord and build SQL queries to make the associations work.

That said, you can make it look like there is an association, you just have to write your own methods. Which was the up-voted answer on that question you linked to.

So, add a column to your Contact model that is user_id or whatever key you need to pass to your User.find ActiveResource model and you could part of the association contract like this:

class User < ActiveResource::Base
  # boilerplate ActiveResource url stuff

  def contacts
    Contact.find(:all, :conditions => { :user_id => self.id })
  end
end

class Contact < ActiveRecord::Model
  def user
    User.find_by_user_id(self.user_id)
  end
end

There's a lot more you get from has_many for free, but that's the gist of it.

Otto