views:

364

answers:

1

I'm trying to create ActiveResource objects for three objects in an internal application.

There are Tags, Taggings, and Taggables:

http://tagservice/tags/:tag
http://tagservice/taggings/:id
http://tagservice/taggables/:type/:key

Tag's :tag is the URL-encoded literal tag text. Tagging's :id is an autoincremented integer. Taggable's :type is a string. There is no finite set of taggable types -- the service can support tagging anything. Taggable's :key is the ID field that the service for that Taggable's type assigns. It could be a business value, like an emplyee's username, or simply an autoincremented integer.

If these were ActiveRecord objects, I'd code them something like this:

class Tag < ActiveRecord::Base
  has_many :taggings
  has_many :taggables, :through => :taggings
  def self.find_by_id(id)
    find_by_name(id)
  end
  def to_param
    CGI::escape(self.name)
  end
end

class Tagging < ActiveRecord::Base
  belongs_to :tag
  belongs_to :taggable
end

class Taggable < ActiveRecord::Base
  has_many :taggings
  has_mnay :tags, :through => :taggings
  def self.find_by_id(id)
    find_by_type_and_key(*id.split('/'))
  end
  def to_param
    "#{self.type}/#{self.key}"
  end
end

Does anyone know what those classes would like like in ActiveResource? Thanks!

+1  A: 

Are you using Rails 3.0 ? If that's the case, then you can almost do exactly the same thing in ActiveResource now.

If not, consider trying hyperactive resource: http://github.com/taryneast/hyperactiveresource

Which I extended to make ActiveResource work almost the same as Active Record. It supports associations, just like AR - though it does not support "through" - you may have to hand-code that eg for a Baz that has_many :foos, :through => :bars you'd do:

# ugly, but does the job
def foos
  return [] unless bars.present?
  foo_set = []
  self.bars.each {|b| foo_set += b.foos }
  foo_set
end
Taryn East