我有三种模式:帖子,问题和评论(评论属于问题和问题属于帖子),并且试图在评论索引页上显示最后2个问题。
这里是我的comments_index功能:未定义的方法'问题'
def index
@question = Question.find params[:question_id]
@comments = @question.comments
@questions = @comment.questions.order(:created_at).limit(2).reverse_order
end
和我comments_index:
<% @questions.each do |question| %>
<%= question.body %>
<% end %>
这里是我得到的错误:
undefined method `questions' for nil:NilClass
我的routes.rb文件看起来像这样:
resources :posts do
resources :questions do
end
end
resources :questions do
resources :comments do
end
end
谢谢你的作品,除了我希望它是属于帖子的最后2个问题。对不起,如果我不够清楚。我认为你对我的路线是正确的,我会改变这一点。 – user2759575
so ...'@ question.post.questions.order(:created_at).last(2)'。可能甚至想要将'@ post'作为实例变量在视图中使用?所以...'@post = @ question.post'。然后'@ post.questions'等 – Dudo