【发布时间】:2018-03-16 15:30:35
【问题描述】:
这在某些时候有效,但我不知道出了什么问题或如何纠正路线。
我在我的索引页面上得到以下信息: NoMethodError in Admin::Locations#index undefined method `name' for nil:NilClass
它来自以下:
<tbody>
<% @locations.each do |location| %>
<tr>
<td><%= location.name %></td>
<td><%= location.state %></td>
<td><%= location.region.name %></td>
</tr>
<% end %>
</tbody>
特别是 location.region.name。我的位置控制器如下所示:
class Admin::LocationsController < Admin::ApplicationController
belongs_to_app :locations
add_breadcrumb 'Locations', :admin_locations_path
before_action :load_location, only: [:show, :edit, :update, :destroy]
def index
@locations = Location.ordered.paginate(page: params[:page])
@locations = @locations.search(params[:search]) if params[:search]
respond_with @locations
end
def show
respond_with @location
end
def new
@location = Location.new
respond_with @location
end
def create
@location = Location.new(location_params)
flash[:notice] = 'Location created successfully' if @location.save
respond_with @location, location: admin_locations_path
end
def edit
respond_with @location
end
def update
flash[:notice] = 'Location updated successfully' if @location.update_attributes(location_params)
respond_with @location, location: admin_locations_path
end
def destroy
flash[:notice] = 'Location deleted successfully' if @location.destroy
respond_with @location, location: admin_locations_path
end
private
def load_location
@location = Location.find_by!(id: params[:id])
end
def location_params
params.require(:location).permit(:name, :hours_operation, :abbreviation, :address_1, :address_2, :city, :state,
:postal_code, :phone, :fax, :region, :region_id)
end
end
现在如果我将location.region.name 更改为location.region,它实际上会生成类似
#<Region:0x0005223ac5>
真的只有一个区域被应用,所以我很茫然。
【问题讨论】:
-
“这在某些时候有效,但我不知道出了什么问题” - 在我进一步阅读之前:如果您使用 git(或其他版本控制系统),只需返回最后一个已知的工作提交并重试。如果您不使用版本控制,请放弃所有内容并现在学习基础知识。它是现代开发人员必不可少的工具。
-
你是什么意思,“如果我改变
location.region.name”? -
我确实回去了,无法辨别导致这种情况的任何变化。这令人难以置信的沮丧。我确实在我的控制器中看到了一个小变化,但我更新了它,但仍然是一个问题。
-
如果我使用 location.region 我得到了一代。如果我使用 location.region.name 我得到错误。我更新了问题。
-
啊,但是如果您只使用
location.region,您是否对所有 位置都有这个功能?我打赌你 10 美元,至少有一个地方没有这个。 (意味着这个位置的区域是nil。也意味着这是一个数据问题,回滚代码可能无济于事)
标签: ruby-on-rails