轨道 5 - 显示路线不工作或生成



我正在深入研究rails 5.2.0。我正在开发一个死的简单应用程序,让我的脚湿透任何新东西(主要是在带有 rails 3 和 4 应用程序的生产中工作)。

我在我的索引路径上,渲染类似的东西

<ul>
<% @questions.each do |question| %>
<li><%= link_to question.title, questions_path(question.id) %></li>
<% end %>
</ul>

我的控制器看起来像

def index
@questions = Question.all
end
def new
@question = Question.new
end
def create
@question = Question.new(title: params['question']['title'], body: params['question']['body'])
if @question.save 
redirect_to '/'
else
redirect_to '/questions/new'
end
end
def show
@question = Question.find(params[:id])
end

我的路线看起来像

get '/' => 'questions#index'
get '/questions/new' => 'questions#new'
post '/questions' => 'questions#create'
get '/questions/:id' => 'questions#show'

这一切都很好,但是当我去单击索引中的链接时,我得到了一个http://localhost:3000/questions.8的路径,当我运行rails routes时,我得到

Prefix Verb URI Pattern                                                                              Controller#Action
GET  /                                                                                        questions#index
GET  /questions/:id(.:format)                                                                 questions#show
questions_new GET  /questions/new(.:format)                                                                 questions#new
questions POST /questions(.:format)                                                                     questions#create

如果您注意到它没有为显示路由生成路径。唯一有效的就是在索引中做这样的事情

<% @questions.each do |question| %>
<li><%= link_to question.title, "/questions/#{question.id}" %></li>
<% end %>

这很好,但违背了这些路线的全部目的。

有没有人看到我做错了什么或忘记了什么?这是 rails 5 的事情,还是只是我的代码中的愚蠢的东西?

你的问题是questions_path路由到/questions,所以当你这样做时,

link_to question.title, questions_path(question.id)

您将question.id追加为.8/questions(因为questions_path不需要参数)。

相反,你不应该只做:

root 'questions#index'
resources :questions

这会给你:

root GET    /                                 questions#index
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    

(如果您愿意,可以使用:only:except修剪路线。

然后你可以做:

<ul>
<% @questions.each do |question| %>
<li><%= link_to question.title, question %></li>
<% end %>
</ul> 

Rails 应从question变量推断出正确的路由,并创建指向/questions/8的链接,如文档中所述。

您应该将显示路由定义为

get '/questions/:id' => 'questions#show', :as => :question 

然后将其用作question_path(question)(注意没有复数),因为questions_path已被路由带到questions#index

但是,如果您想要更清洁的解决方案,最好使用rails的路线辅助方法resources

resources :questions, :only => [:index, :new, :create, :show] 

最新更新