Can ActiveResource models integrate with ActiveRecord models?

I am working on a Rails application that will serve as an authentication system for other Rails applications through the Rails ActiveResource functionality.

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

But what if I want to put User model has_many :contacts or something like that in my client application ( contacts is an ActiveRecord model in the client application)? Then I would like to do things like get all the Contact that belong to some User .

Is it possible?

(I noticed that a similar question was asked , but there were not many answers.)

+4
source share
2 answers

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

However, you can make it look like an association exists, you just need to write your own methods. What was the interviewed answer to this question that you contacted.

So, add a column to your contact model, which is in user_id , or any other key that you need to pass into your User.find ActiveResource model, and you can include the association contract as follows:

 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 

The more you get from has_many for free, but its essence.

+5
source

This question is ancient, but I met this recently:

http://yetimedia.tumblr.com/post/35233051627/activeresource-is-dead-long-live-activeresource

From the post:

Basic association support: has_many, has_one, belongs_to can now be used in ActiveResource models.

There are some other improvements in the publication that may require a second look at ActiveResource, although it has been removed from Rails 4.0.

+3
source

All Articles