我有以下控制器 - recipes_controller.rb:
class RecipesController < ApplicationController
def list
@search_term = params[:looking_for] || 'chicken'
@courses = Recipe.for(@search_term)
end
end
以下型号:recipes.rb:
require 'httparty'
class Recipe
include HTTParty
default_options.update(verify: false)
base_uri 'http://food2fork.com/api/search'
default_params key: ENV['FOOD2FORK_KEY']
format :json
def self.for term
get("", query: { q: term})["recipes"]
end
end
&安培;以下view-list.html.erb:
<h1>Searching for - <%= @search_term %></h1>
<table border="1">
<tr>
<th>Image</th>
<th>Publisher</th>
<th>Title</th>
</tr>
<% @courses.each do |course| %>
<tr class=<%= cycle('even', 'odd') %>>
<td><%= image_tag(course["image_url"])%></td>
<td><%= course["publisher"] %></td>
<td><%= course["title"] %></td>
</tr>
<% end %>
</table>
当我执行http://localhost:3000/recipes/list时,它会给我以下错误:
814:&#39; FORBIDDEN&#39;
的意外令牌应用程序跟踪|框架跟踪|完整追踪
app / models / recipe.rb:13:for'
app/controllers/recipes_controller.rb:4:in
列表&#39;
json的格式如下:
{"count": 1, "recipes": [{"publisher": "Tasty Kitchen", "f2f_url": "http://food2fork.com/view/459b3d", "title": "End the Search Chocolate Chip Cookies", "source_url": "http://tastykitchen.com/recipes/desserts/end-the-search-chocolate-chip-cookiese280a6/", "recipe_id": "459b3d", "image_url": "http://static.food2fork.com/cookie2410x307a33e.jpg", "social_rank": 34.80777735743579, "publisher_url": "http://tastykitchen.com"}]}
请让我知道该怎么做。
答案 0 :(得分:1)
好的,我刚刚去注册了food2fork.com api密钥并阅读了他们的文档,你的代码存在一些问题。
如果您查看搜索api文档,您会看到查询参数的说明:
q: (optional) Search Query (Ingredients should be separated by commas). If this is omitted top rated recipes will be returned.
这意味着您正在发送一份包含“关键字”成分的食谱请求以及您正在制作的每个请求。显然,没有配方名为关键字的配方。
如果查看同一部分,“字段”似乎没有查询参数,因此您不应添加它们。它没有伤害,但为什么代码在你的课堂上什么都不做?
您可能希望从环境中获取密钥,而不是将其硬编码到您的应用中。
所有这一切,我认为你想要这样的东西作为你的食谱类:
require 'httparty'
class Recipe
include HTTParty
default_options.update(verify: false)
base_uri 'http://food2fork.com/api/search'
default_params key: ENV['FOOD2FORK_KEY']
format :json
def self.for term
get("", query: { q: term })["recipes"]
end
end