Nil id导致路由问题

时间:2013-10-28 05:10:57

标签: ruby-on-rails ruby-on-rails-4

我有3个模型:帖子,评论和问题。评论属于帖子,问题属于评论。我正在尝试从我的帖子显示页面链接到我的问题显示页面。帖子显示页面正在调用链接所在的部分_comments。问题是链接转到问题索引而不是问题显示,因为question.id是nil。 URL如下所示:

/comments/19/questions/ 

路线:

comment_question GET    /comments/:comment_id/questions/:id(.:format)          questions#show
comment_questions GET    /comments/:comment_id/questions(.:format)            questions#index

_comments partial中的链接:

<%= div_for(comment) do %>
<% comment.questions.select(:title).order('created_at desc').limit(3).each do |question| %>  
<%= link_to question.title, comment_question_path(comment, question) %>
<% end %>
<% end %>

在帖子显示页面中调用partial:

<%= render :partial => @post.comments %>

我将链接更改为:

<%= url_for :controller => 'questions', :action => 'show', :comment_id => comment.id, :id => question.id %>

但得到了这个错误:

 No route matches {:action=>"show", :controller=>"questions", :id=>nil, :comment_id=>20}

感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

你的问题不是零,问题对象没有附加ID。

<% comment.questions.select(:title).order('created_at desc').limit(3).each do |question| %>

该行将构建类似于以下内容的查询(忽略与注释的连接):

SELECT title FROM questions

当您将其传递给comment_question_path(comment, question)时,它只读取属性,它不会尝试从数据库中获取它。该问题对象中的ID将为nil,因为您尚未查询该ID,因此为什么它会使用零问题ID构建链接。

如果您确实想使用select,请改用comment.questions.select([:id, :title])

如果您不关心使用select,请改用comment.questions

有关select的更多信息:http://guides.rubyonrails.org/active_record_querying.html#selecting-specific-fields