简体   繁体   English

Ruby on Rails - nil:NilClass 错误的未定义方法`each'

[英]Ruby on Rails - undefined method `each' for nil:NilClass error

I've gone over the API for my specific error and the answers provided are not able to solve my issue.我已经针对我的特定错误检查了 API,所提供的答案无法解决我的问题。

I'm just experimenting with a "find nearest location" code obtained online, and my issue is that when I am implementing this code to a project, I am obtaining the "undefined method `each' for nil:NilClass error".我只是在尝试使用在线获得的“查找最近的位置”代码,我的问题是当我将此代码实施到项目时,我获得了“未定义的方法 `each' for nil:NilClass 错误”。

I understand this error would be due to, when calling an @something, it isn't defined.我知道此错误是由于在调用 @something 时未定义。 So, this is the code and files I'm working with:所以,这是我正在使用的代码和文件:

locations.rb位置.rb

class Nearby_Location < ActiveRecord::Base
  geocoded_by :full_address
  after_validation :geocode, :if => :address_changed?

  def full_address
   [address, city, postcode].compact.join(',')
  end
end

locations_controller.rb location_controller.rb

class Locations < ApplicationController
  def index
    @locations = Locations.all
    if params[:search].present?
      @locations = Locations.near(params[:search], 10, :order => :distance)
    else
      @locations = Locations.all.order("created_at DESC")
    end
  end

  def new
    @locations = Locations.new
  end

  def create
    @locations = Locations.new(location_params)
    if @locations.save
      flash[:success] = 'Place added!'
      redirect_to root_path
    else
      render 'new'
    end
  end

  def location_params
    params.require(:location).permit(:company_name, :address, :city,
                                    :postcode, :latitude, :longitude)
  end

  def show
    render :layout => nil
    @locations = Locations.find(params[:id])
  end

end

page.html.erb页面.html.erb

<div class="container">
  <div class="starter-template">
    <h3>Find places near your location</h3>
    <p class="lead">Enter your address or zip code</p>
    <p><%= form_tag locations_path, :method => :get do %>
      <%= text_field_tag :search, params[:search], placeholder: "e.g Statue of Liberty, New York" %>
      <%= submit_tag "Search Near", :name => nil %>
      <% end %>
    </p>
  </div>

  <% @locations.each do |locations| %>
 <%= link_to locations do %>
  <%= locations.name %>
 <% end %>
<% end %>

</div>
</div>

scheme.rb方案.rb

  create_table "locations", force: :cascade do |t|
    t.string "address"
    t.float "latitude"
    t.float "longitude"
  end

I've modified with the code incorporating the answers of the other APIs but with no success.我已经修改了包含其他 API 答案的代码,但没有成功。 I feel it may be due to the def show portion of the code, but I'm not too sure.我觉得这可能是由于代码的 def show 部分,但我不太确定。

You did not specify which controller action you hit this error in, however based off your code I guess it is from the show method.您没有指定您遇到此错误的控制器操作,但是根据您的代码,我猜它来自show方法。 The issue is probably that you are trying to not render the layout, however you are doing this before setting the @locations variable.问题可能是您试图不呈现布局,但是您是在设置@locations变量之前这样做的。 Therefore, Rails is going into rendering before the instance variable has been created.因此,Rails 会在创建实例变量之前进行渲染。 To fix, you should move render :layout => nil line to the end of your method, after the instance variables have been created, eg:要修复,您应该在创建实例变量后将render :layout => nil行移动到方法的末尾,例如:

def show
  @locations = Locations.find(params[:id])
  render :layout => nil
end

However, I think you may not be fully understanding the flow of events happening here based off the names of your files.但是,我认为您可能无法根据文件名称完全理解此处发生的事件流。 By default, at the end of a controller action, Rails will attempt to render a file by looking for a file name matching the controller action from within a views folder matching the name of the controller.默认情况下,在控制器操作结束时,Rails 将尝试通过从与控制器名称匹配的视图文件夹中查找与控制器操作匹配的文件名来呈现文件。 For example:例如:

app/controllers/books_controller.rb :应用程序/控制器/books_controller.rb

class BooksController < ApplicationController
  def index
    # Will automatically render `app/views/books/index.html.erb`
  end

  def show
    render :other_show_page # Will look for a file `app/views/books/other_show_page.html.erb` rather than `app/views/books/show.html.erb` because it was explicitly specified
  end
end

In your case, you have a file called page.html.erb but you do not have a controller action ( def page; end ) nor are any of your other actions specifically rendering a file called page .在您的情况下,您有一个名为page.html.erb的文件,但您没有控制器操作( def page; end ),也没有任何其他操作专门呈现名为page的文件。 As such, Rails would not be able to find your page.html.erb file anyway.因此,Rails 无论如何都无法找到您的page.html.erb文件。 I assume you do have a show.html.erb file or else you would be getting a different error, however if you are trying to render the HTML from within your page.html.erb file, it will not happen from within your show method unless you specifically render that file.我假设你确实有一个show.html.erb文件,否则你会得到一个不同的错误,但是如果你试图从你的page.html.erb文件中呈现 HTML,它不会在你的show方法中发生除非您专门渲染该文件。

A few other notes...其他一些注意事项...

  • Models should typically have names in the singular, rather than plural.模型的名称通常应该是单数,而不是复数。 You appear to be using Locations as your model name, rather than Location .您似乎使用Locations作为模型名称,而不是Location
  • Your instance variable in your show method @locations , though you are using the find ActiveRecord query.您的show方法@locations实例变量,尽管您使用的是find ActiveRecord 查询。 This query returns a single object, rather than a collection proxy of many objects.此查询返回单个对象,而不是多个对象的集合代理。 As such, your @locations variable naming is slightly misleading, and may be better as @location .因此,您的@locations变量命名有点误导,可能比@location更好。
  • If you are trying to render the page.html.erb file when you hit the show method, unless there is some specific reason you are doing this it is unnecessary and bad practice.如果想使page.html.erb文件时,你打的show方法,除非有你这样做是不必要的,不好的做法,一些具体的原因。 You should just include the code in a show.html.erb file and let Rails automatically render it rather than creating a custom file that you are rendering specifically.您应该只将代码包含在show.html.erb文件中,并让 Rails 自动呈现它,而不是创建您专门呈现的自定义文件。 Rails is convention over configuration, so try to learn the conventions and follow them until you have a good reason to break away. Rails 是约定优于配置,所以尝试学习约定并遵循它们,直到您有充分的理由脱离。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM