【发布时间】:2014-01-03 21:00:19
【问题描述】:
我认为在尝试保存到我的数据库时没有访问我的辅助方法。正在创建一个新的 Airport 实例,但我期望从 API 获得的数据不存在。它应该根据用户在视图中的 form_for 中输入的 IATA 代码引入机场名称。
换句话说,“名称”在我的数据库中始终为零。因此,似乎根本没有使用 API,并且名称从未发送到控制器进行保存,这使我相信由于某种原因没有调用帮助程序。
如果真的被调用了,为什么“name”没有被填写?
这是我的控制器:
class AirportsController < ApplicationController
include AirportsHelper
def new
@airport = Airport.new
end
def create
new_airport = Airport.create(params[:airport])
if new_airport.errors.empty?
create_location(params[:airport][:code]) #should call the create_location method in AirportsHelper
redirect_to airport_path(new_airport.id)
else
flash[:notice] = new_airport.errors.full_messages
redirect_to new_airport_path
end
end
def show
@airport = Airport.find(params[:id])
end
end
这是我的帮助文件:
module AirportsHelper
def create_location(airport_code)
airport = Airport.find_by_code(airport_code) #looks up db based on arpt code
result = Typhoeus.get("https://api.flightstats.com/flex/airports/rest/v1/json/iata/#{airport}?appId=[APP ID]&appKey=[APP KEY]")
result_hash = JSON.parse(result.body)
result_hash['airports'].each do |airport|
@airport_name = airport['name']
end
Airport.update_attributes(name: @airport_name, airport_id: airport.id)
Location.create(name: @airport_name, airport_id: airport.id)
airport.update_attributes(name: @airport_name)
airport.save
end
end
这是我的表单(部分内置):
<%= form_for @airport do |f| %>
<%= f.text_field :city, :placeholder => "City" %> <p>
<%= f.text_field :country, :placeholder => "Country" %> <p>
<%= f.text_field :code, :placeholder => "3-letter code" %> <p>
<%= f.text_area :details, :placeholder => "Airport details" %> <p>
<%= f.submit %>
<% end %>
模型具有正确的属性:
class Airport < ActiveRecord::Base
attr_accessible :city, :code, :country, :details, :name
end
我听说在控制器中调用助手不是一个好习惯,但我不知道把它放在哪里以便在正确的时间调用它。
我仍在快速掌握 Rails,因此我们将不胜感激任何调试帮助!
【问题讨论】:
-
使用固定的错字,得到这个错误:JSON::ParserError in AirportsController#create 757: 'status: 404 code: NOT_FOUND message: Resource not found. '
标签: ruby-on-rails ruby helper