這是active.rb
class active < ActiveResource::Base
self.site = "http://localhost:3002/api/v1/users" # **當我運行這個時,它沒有取到資料**。
self.site = Net::HTTP.get(URI.parse("http://localhost:3002/api/v1/users"/span>) # **當我運行這個時,我可以在控制臺看到資料。會得到錯誤的壞URI**。
end
welcome_controller.rb
def index
@active = Active.all
end
我無法從使用活動資源中獲取資料。請讓我知道 謝謝你
uj5u.com熱心網友回復:
我懷疑ActiveResource沒有發出你所期望的請求。
Active.collection_path和Active.element_path
對于前者,你會看到"/api/v1/users/actives.json",因為activeresource期望Active類是你的資源名稱。
你可以通過覆寫ActiveResource的兩個方法來控制生成的URI并移除資源規范(即.json)
class Active < 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)}#{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)}#{query_string(query_options)}"
end
end
self.site = "http://localhost:3002/"/span>
self.prefix = "/api/v1/users"/span>
結束。
這將給你一個集合路徑/api/v1/users
也許一個更干凈的選擇是使用self.element_name = "users",檔案表明,這" 在你已經有一個與所需的RESTful資源同名的現有模型的情況"
您還可以通過使用self.include_format_in_path = false來移除格式(.json),正如這里提到的。
所以你可以通過使用:
來達到同樣的效果class Active < ActiveResource::Base
self.include_format_in_path =false
self.site = "http://localhost:3002/"/span>
self.prefix = "/api/v1/".
self.element_name = "users"。
結束。
作為一個旁觀者,我想鏈接到這個答案,它有一些非常有用的關于定制ActiveResource的筆記,而不需要求助于猴子打補丁。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/313835.html
標籤:
