控制器无法访问辅助方法

时间:2014-01-03 21:00:20

标签: ruby-on-rails ruby helper

我不认为在尝试保存到我的数据库时正在访问我的帮助方法。正在创建一个新的机场实例,但我期望从API获得的数据不存在。它应该根据用户在视图中的form_for中输入的IATA代码引入机场的名称。

换句话说,我的数据库中“name”总是为nil。因此看起来似乎根本没有使用API​​,并且名称永远不会发送到控制器进行保存,这使我相信由于某种原因没有调用帮助程序。

如果它实际被调用,为什么“名字”没有被填充?

这是我的控制者:

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加速,所以任何调试帮助都会受到赞赏!

2 个答案:

答案 0 :(得分:1)

你的create_location方法中有一个拼写错误,'aiports'代替'airports'

答案 1 :(得分:0)

想出来了!

原来帮助方法工作得很好。所以任何人都在寻找帮助器模块的问题,这可能是一个很好的参考工作。

问题在于@PeterAlfvin建议的JSON调用。它没有采取正确的数据。

这是正确的辅助方法:

module AirportsHelper
  def create_location(airport_code)
    airport = Airport.find_by_code(airport_code)

    result = Typhoeus.get("https://api.flightstats.com/flex/airports/rest/v1/json/iata/#{airport_code}?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.save

  end
end 

请注意API get请求中的字符串插值更改。

相关问题