這是活動的.rb
class Active < ActiveResource::Base
self.site = "http://localhost:3002/api/v1/users" # **When i run this it is not fetching data**
self.site = Net::HTTP.get(URI.parse("http://localhost:3002/api/v1/users")) # **When i run this i can see the data in console. Will get error Bad URI**
end
歡迎控制器.rb
def index
@active = Active.all
end
我無法從正在使用的活動資源中獲取資料。請告訴我謝謝
uj5u.com熱心網友回復:
我懷疑 ActiveResource 沒有發出您期望的請求。您可以通過在 Rails 控制臺中運行以下命令來獲得一些清晰的資訊:
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/"
self.prefix = "/api/v1/users"
end
這會給你一個收集路徑 /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/"
self.prefix = "/api/v1/"
self.element_name = "users"
end
順便說一句,我想鏈接到這個答案,它有一些關于自定義 ActiveResource而不求助于猴子補丁的非常有用的注釋。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/416233.html
標籤:
