如何在使用活动资源时从url中删除.xml和.json

lee*_*ava 11 ruby-on-rails

当我在活动资源中进行映射时,它对Ruby on Rails的默认请求总是自动在URL的末尾添加扩展.例如:我想通过映射从Ruby on Rails获取用户资源,如下所示:

class user < ActiveResource::Base
  self.site = 'http://localhost:3000'
end

我需要的东西,我只是希望它通过没有扩展名的网址

http://localhost:3000/user
相反,它会自动添加网址末尾的扩展名
http://localhost:3000/user.xml

当我从活动资源映射发出请求时,如何省略url的扩展名?

Jer*_*iah 12

起初,我确实使用了@Joel AZEMAR的答案,并且在我开始使用PUT之前它运行良好.在.json/.xml中添加PUT.

这里的一些研究表明,使用该ActiveResource::Base#include_format_in_path选项对我来说效果更好.

没有include_format_in_path:

class Foo < ActiveResource::Base
  self.site = 'http://localhost:3000'
end

Foo.element_path(1)
=> "/foo/1.json"
Run Code Online (Sandbox Code Playgroud)

使用include_format_in_path:

class Foo < ActiveResource::Base
  self.include_format_in_path = false
  self.site = 'http://localhost:3000'
end

Foo.element_path(1)
=> "/foo/1"
Run Code Online (Sandbox Code Playgroud)

  • 这很好用,比其他解决方案更清洁.谢谢. (2认同)

Car*_*ino 4

您可以通过重写类中的两个 ActiveResource 方法来做到这一点:

class User < 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}/#{id}#{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://localhost:3000'
end
Run Code Online (Sandbox Code Playgroud)