【问题标题】:Undefined method or local variable in railsrails中未定义的方法或局部变量
【发布时间】:2019-09-02 05:52:18
【问题描述】:
undefined local variable or method `requestuser_path' for #<#<Class:0x007f92de073e10>:0x007f92e191a020>

我不知道为什么会出现这个错误,即使我路由到所需的控制器并且这里的视图也没有问题。

# routes.rb

resources :users do 
  member do
    get :following, :followers
  end
end

resources :sessions, only: [:new, :create, :destroy]
resources :microposts, only: [:create, :destroy]
resources :relationships, only: [:create, :destroy]
#resources :requests, only: [:create]

root to: 'static_pages#home'

match '/signup',  to: 'users#new'
match '/signin',  to: 'sessions#new'    
match '/signout', to: 'sessions#destroy', via: :delete
match '/help',    to: 'static_pages#help'
match '/about',   to: 'static_pages#about'
match '/request', to: 'users#requestuser'

命名路线:

<% if signed_in? %>
  <li><%= link_to "Requests", requestuser_path %></li>
<% end %>

用户控制器:

def requestuser
  @title = "Requests"
  @user = User.find(params[:id])
  @users = @user.followed_users.paginate(page: params[:page])
end

我认为命名路线中存在错误,因为我是 Rails 新手。我不知道错误的原因是什么。命名路由是预定义的或者它是如何工作的。

我需要学习更多关于 Rails 的主题,谁能告诉我在初学者阶段之后哪个是最好的学习网站。

【问题讨论】:

  • Rails 的版本是多少?
  • 你没有在任何地方定义requestuser命名路由,所以难怪你会出错。
  • 如果您不确定存在哪些路由或它们的命名方式,可以在控制台中使用rails routes
  • 试试这个:- match '/request', to: 'users#requestuser', via: [:get, :post], as: :requestuser, 你的代码将按原样工作,无需任何更改,只需在您的路线中添加 as: :requestuser

标签: ruby-on-rails ruby routes


【解决方案1】:

requestuser_path 路由辅助方法不存在。

除非指定,否则路由辅助方法会在 Rails 中自动生成。要查看所有这些帮助程序及其相应控制器和操作的列表,请转到http://localhost:3000/rails/info/routes,假设您在端口 3000 上运行开发 Rails 服务器。

在您的情况下,您正在寻找的方法是request_path,而不是requestuser_path

要了解有关 Rails 中路由的更多信息,官方文档是一个很好的资源。 https://guides.rubyonrails.org/routing.html

【讨论】:

  • 虽然我给了 users#requestuser,但它为什么会寻找 request_path
【解决方案2】:

尽量不要使用 ruby​​ 关键字作为路由或任何控制器或模型的名称。 Ruby 会抛出错误。尝试将路由“匹配'/request',重命名为:'users#requestuser'”

【讨论】:

    【解决方案3】:
    1. 运行rails routesrake routes 以查看rails 如何生成您的路线始终是一个好习惯,在您的情况下,请使用request_path

    2. 不建议使用match,甚至在较新的rails版本中被认为无效:

    如果您想将您的操作同时暴露给 GET 和 POST,请添加 via: [:get, :post] 选项。 如果您想向 GET 公开您的操作,请在路由器中使用 get: 而不是:匹配“controller#action” 做:获取“controller#action”

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-04-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多