【问题标题】:How do I use ActiveResource with a custom URL scheme?如何将 ActiveResource 与自定义 URL 方案一起使用?
【发布时间】:2009-05-16 17:16:34
【问题描述】:

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

Tags、Taggings、Taggables:

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

Tag:tag 是 URL 编码的文字标记文本。 Tagging:id 是一个自动递增的整数。 Taggable:type 是一个字符串。没有有限的可标记类型集——该服务可以支持标记任何东西。 Taggable: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 中的这些课程喜欢什么?谢谢!

【问题讨论】:

  • 我的回答有帮助吗?如果是这样,你能接受吗? :) 如果没有,请告诉我你最终做了什么。

标签: ruby-on-rails ruby activerecord rest activeresource


【解决方案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

【讨论】:

    猜你喜欢
    • 2014-03-02
    • 2015-04-06
    • 2011-01-21
    • 1970-01-01
    • 1970-01-01
    • 2017-11-09
    • 2021-05-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多