Ruby on Rails实例变量未通过表单提交设置

时间:2014-10-22 02:28:55

标签: ruby-on-rails

我的应用程序以一个以字符串作为您的位置的表单开始,在单击提交时,它应该将此字符串传递给gem-api调用,该调用将返回一个json数组,然后我将其解析并显示。我遇到的问题是单击“提交”将实例变量保留为nil。

以下是您在第一页上看到的表单:

<%= form_for @location do |f| %>
  <%= f.label :address %>
  <%= f.text_field :address, :placeholder => "City State" %>
  <br>
  <%= f.submit "Find Coffee!" %>
<% end %>

这是控制器的代码:

class LocationsController < ApplicationController
  before_action :set_location, only: [:show, :edit, :update, :destroy]

  # GET /locations
  # GET /locations.json
  def index
    @location = Location.new
  end

  # POST /locations
  # POST /locations.json
  def create
    @shops = []
    @client = GooglePlaces::Client.new('###API KEY####')
    @shops = @client.spots_by_query('coffee near ' + @location.address)
  end

  private
    # Never trust parameters from the scary internet, only allow the white list through.
    def location_params
      params.require(:location).permit(:address)
    end
end

那么当我填写表单并单击提交时会发生什么?我得到一个未定义的方法@ location.address为nil,当我在rails控制台中设置它时它按照我的意愿工作,所以它只是一个获取@location = Location.new然后将地址传递给它的问题。我错过了什么?

1 个答案:

答案 0 :(得分:0)

您在一个操作中定义的变量不会在另一个操作中定义。它们是完全不同的记忆块。

  def create
    @shops = []
    @client = GooglePlaces::Client.new('###API KEY####')
    @shops = @client.spots_by_query('coffee near ' + @location.address)
  end

应该是

  def create

    @shops = []
    @location = Location.create(location_params)
    @client = GooglePlaces::Client.new('###API KEY####')
    @shops = @client.spots_by_query('coffee near ' + @location.address)
  end