1

我正在尝试为ActiveResource内部应用程序中的三个对象创建对象。

Tags、Taggings 和Taggables:

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

Tag's:tag是 URL 编码的文字标记文本。 Tagging's:id是一个自动递增的整数。 Taggable's:type是一个字符串。没有有限的可标记类型集——该服务可以支持标记任何东西。 Taggable's:key是该Taggable类型的服务分配的 ID 字段。它可以是业务价值,例如员工的用户名,或者只是一个自动递增的整数。

如果这些是ActiveRecord对象,我会将它们编码为:

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

有谁知道这些课程想要什么ActiveResource?谢谢!

4

1 回答 1

1

你在使用 Rails 3.0 吗?如果是这样的话,那么你现在几乎可以在 ActiveResource 中做同样的事情了。

如果没有,请考虑尝试超活跃资源:http: //github.com/taryneast/hyperactiveresource

我扩展它以使 ActiveResource 的工作方式与 Active Record 几乎相同。它支持关联,就像 AR 一样 - 虽然它不支持“通过” - 你可能必须手动编码,例如对于 has_many :foos, :through => :bars 你会做的 Baz:

# ugly, but does the job
def foos
  return [] unless bars.present?
  foo_set = []
  self.bars.each {|b| foo_set += b.foos }
  foo_set
end
于 2010-08-31T10:28:10.823 回答