使用ActiveResource更改URL

时间:2011-06-17 19:01:06

标签: ruby-on-rails-3 url activeresource

我正在使用ActiveResource来管理访问外部服务。

外部服务的网址如下:

http://api.cars.com/v1/cars/car_id/range/range_num?filter=filter1,filter2

这是我的Car类:

    class Car < ActiveResource::Base                                                                                 

          class << self                                                                                                                                                                 
            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.parser.escape id.to_s}#{query_string(query_options)}"                                                                  
                end                                                                                                                                                                         

                def collection_path(prefix_options = {}, query_options = nil)                                                                                                               
                  prefix_options, query_options = split_options(prefix_options) if query_options.nil?                                                                                       
                  "#{prefix(prefix_options)}#{collection_name}#{query_string(query_options)}"  
    end                                                                                                  end                              

self.site = "http://api.cars.com/"                                                                     
self.prefix = "/v1/"
self.format = :json

end

当我设置我的对象以在rails控制台中获取特定的汽车时:

> car = car.new
> car.get('1234')

我得到这样的网址:

http://api.cars.com/v1/cars//1234.json

如何获取包含range和range_num元素的URL?

另外,我不希望URL的末尾有.json扩展名。我试图覆盖这里描述的element_name和collection_name方法:How to remove .xml and .json from url when using active resource但它似乎对我不起作用......

提前感谢任何想法!

1 个答案:

答案 0 :(得分:0)

删除网址中的正斜杠

 "#{prefix(prefix_options)}#{collection_name}/#{URI.parser.escape id.to_s}#{query_string(query_options)}"                                                                   

变为:

"#{prefix(prefix_options)}#{collection_name}#{URI.parser.escape id.to_s}#{query_string(query_options)}"