我收到一条错误消息,说它有
undefined local variable or method 'your_questions_path'
我的routes.rb
文件:
Rails.application.routes.draw do
get "/" => "main_app#index"
get "/location" => "location#location"
post "/location/index" => "location#index"
get "/location/index" => "location#index"
get "/location/directions" => "location#directions"
root to: 'questions#index'
resources :questions do
collection do
get :your_questions
end
end
get '/logout', to: 'sessions#destroy', via: :delete
resources :users, only: [:new, :create]
resources :sessions, only: [:new, :create]
resources :questions, except: [:new] do
resources :answers, only: [:create]
end
get '/register', to: 'users#new'
get '/login', to: 'sessions#new'
get '/logout', to: 'sessions#destroy', via: :delete
# get '/questions/your_questions', to: 'questions#your_questions' original
get '/questions/:id', to: 'questions#show'
get 'search', to: 'controller#action', as: :search
我的视图文件包含问题路径a.k.a app/views/layouts/application.html.erb
<div id="nav">
<ul>
<li>
<%= link_to 'Home', root_path %>
</li>
<% if logged_in? %>
<li>
<%= link_to "Your Q's", your_questions_path %>
</li>
<li>
<%= link_to "Logout (#{current_user.username})", logout_path, method: 'get' %>
</li>
<% else %>
<li>
<%= link_to 'Register', register_path %>
</li>
<li>
<%= link_to 'Login', login_path %>
</li>
我希望问题路径转到http://localhost:3000/questions/1
提前谢谢!
答案 0 :(得分:3)
您定义的路线会创建以下路线:
your_questions_questions GET /questions/your_questions(.:format) questions#your_questions
questions GET /questions(.:format) questions#index
POST /questions(.:format) questions#create
new_question GET /questions/new(.:format) questions#new
edit_question GET /questions/:id/edit(.:format) questions#edit
question GET /questions/:id(.:format) questions#show
PATCH /questions/:id(.:format) questions#update
PUT /questions/:id(.:format) questions#update
DELETE /questions/:id(.:format) questions#destroy
顶部路线是your_questions
路线,这意味着您需要使用:
your_questions_questions_path
答案 1 :(得分:0)
这种情况正在发生,因为你已经在资源块中嵌套了你的路径,即。你有这个:
resources :questions do
collection do
get :your_questions
end
end
如果你要到达这条路径,(运行rake routes
)你需要使用questions_your_questions_path,但是因为你想要路由到类似http://localhost:3000/quesitons/1
的东西,这是一个简单的'show'路径,由resources命令提供给您,而是将您的路径文件改为简单地说:
resources :questions
然后使用question_path(@question)
,其中@question是控制器中设置的实例变量。
然而......也从您的代码中看,您似乎想要questions_path
,因为这会提供index
操作(问题列表)。然后,您可以在控制器范围内将问题集合添加到当前用户看到的那些......
即。
QuestionsController < ApplicationController
def index
@questions = current_user.questions
end
(假设您的User
has_many:问题)