明确定义的 Rails 路由问题 - Nil:NilClass 的未定义方法

发布于 2024-09-02 04:53:05 字数 980 浏览 4 评论 0原文

我已经研究这个问题有一段时间了,但仍然没有乐趣。这是我在这个一般领域内的第二个问题,因为最后一个问题太长了,现在这个问题定义得更加明确了。

问题摘要:

我正在为我的客户加载页面,但出现错误:

undefined method 'name' for Nil:NilClass

我的代码

#Link on views/users/show.html.erb:
<%= link_to "Customer Account", :action => "home", :controller => "customers", :id => @user.user_type_id %>

#Regular Route:
map.connect 'customers/home/:id', :controller => 'customers', :action => 'home'

#Rake Routes, first entry:
/customers/home/:id  :controller=>:"customers", :action=>"home"

#Customers Controller:
def home
  render :layout => 'home'
  @customer = Customer.find(params[:id])
  @user = @current_user_session.user
  flash[:error] = "Customer not found" and return unless @customer
  @jobs = @customer.jobs
end

#views/customers/home.html.erb:
<%= @customer.name %>

我完全不知道为什么这个看似清晰的事件序列会导致零级。在控制台中搜索 Customer.find(2) 返回正确的客户。这个菜鸟缺少什么?非常感谢。

I have been working on this problem for a while but still no joy. This is my second question within this general area, because the last question was getting too long and this is now more well-defined.

Summary of the Problem:

I am loading a page for my customers and I get error:

undefined method 'name' for Nil:NilClass

My Code

#Link on views/users/show.html.erb:
<%= link_to "Customer Account", :action => "home", :controller => "customers", :id => @user.user_type_id %>

#Regular Route:
map.connect 'customers/home/:id', :controller => 'customers', :action => 'home'

#Rake Routes, first entry:
/customers/home/:id  :controller=>:"customers", :action=>"home"

#Customers Controller:
def home
  render :layout => 'home'
  @customer = Customer.find(params[:id])
  @user = @current_user_session.user
  flash[:error] = "Customer not found" and return unless @customer
  @jobs = @customer.jobs
end

#views/customers/home.html.erb:
<%= @customer.name %>

I have absolutely no idea why this seemingly clear sequence of events is resulting in a NilClass. Search the console for Customer.find(2) returns the correct customer. What is this noob missing? Thank you very much.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

活雷疯 2024-09-09 04:53:05

您在设置 @customer 之前渲染视图,因此它为零。请尝试以下操作:

def home
  @customer = Customer.find(params[:id])
  @user = @current_user_session.user
  flash[:error] = "Customer not found" and return unless @customer
  @jobs = @customer.jobs
  render :layout => 'home'
end

You are rendering the view before you set @customer, so it is nil. Try the following:

def home
  @customer = Customer.find(params[:id])
  @user = @current_user_session.user
  flash[:error] = "Customer not found" and return unless @customer
  @jobs = @customer.jobs
  render :layout => 'home'
end
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文