2

使用 ActiveResource,对 MyObject.find(id) 的调用将获得“[self.site]/[self.prefix]/:id.[self.format]”。但是,我们访问的 API 的配置略有不同。我们需要访问“[self.site]/:id/[self.suffix].[self.format]”,而不是 id.file_type。

即:获取http://api_path/:id/tool.json

有没有办法为这种情况配置活动资源?我在文档中找不到太多内容。

4

1 回答 1

3

ActiveResource::Base.element_path是创建路径的方法:

def element_path(id, prefix_options = {}, query_options = nil)
  prefix_options, query_options = split_options(prefix_options) if query_options.nil?
  "#{prefix(prefix_options)}#{collection_name}/#{URI.escape id.to_s}.#{format.extension}#{query_string(query_options)}"
end

我将创建一个重新定义 element_path 的类,如下所示:

class CustomApiPath < ActiveResource::Base
  def element_path(id, prefix_options = {}, query_options = nil)
    prefix_options, query_options = split_options(prefix_options) if query_options.nil?
    "#{prefix(prefix_options)}#{URI.escape id.to_s}/#{collection_name}.#{format.extension}#{query_string(query_options)}"
  end
end

(警告:未测试)然后其他 ActiveResource 模型将继承自 CustomApiPath 而不是 ActiveResource::Base。

于 2011-06-06T21:50:51.597 回答