Search code examples
rubyruby-on-rails-3activeresource

Using has_many method in an ActiveResource object to relate to local ActiveRecord objects?


I want to use an ActiveResource object to map Users from a service but I have local data that I want to associate with these Users

I have code that looks something like this:

user.rb:

class User < ActiveResource::Base
  self.site = "http://my/api"

  has_many :notifications, as: :notifiable, dependent: :destroy
  attr_accessible :notifications_attributes
  accepts_nested_attributes_for :notifications, allow_destroy: true
end

notification.rb:

class Notification < ActiveRecord::Base
  belongs_to :notifiable, polymorphic: true
  belongs_to :user
  belongs_to :recipient, class_name: 'User'
end

If ActiveResource doesn't support has_many then how should I go about getting around this?


Solution

  • ActiveResource does support associations but they should be external resource as well. So in your case it doesn't apply.

    I think your requirement is legit and would suggest manually construct methods for them. For example:

    class User < ActiveResource::Base
      self.site = "http://my/api"
    
      def notifications
        Notification.where(user_id: self.id)
      end
    end
    
    class Notification < ActiveRecord::Base
      belongs_to :notifiable, polymorphic: true
    
      def user
        User.find(self.user_id)
      end
    
      def recipient
        User.find(self.recipient_id)
      end
    end