2013-12-12 47 views
0

我有三种模式:帖子,问题和评论(评论属于问题和问题属于帖子),并且试图在评论索引页上显示最后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 

回答

1

问题的has_many评论最后2个问题? 评论belongs_to问题?

如果是这样的话,你只能得到评论的1个问题......但是当你进入问题页面时你已经得到了这个问题......如果你只是想得到最后一个提问2个问题(期间),你可以这样做:

@post = @question.post 
@questions = @post.questions.order(:created_at).last(2) 

这会得到你在数据库中的最后2个问题。

,你的路线......应该不会是:

resources :posts do 
    resources :questions do 
    resources :comments do 
    end 
    end 
end 

+0

谢谢你的作品,除了我希望它是属于帖子的最后2个问题。对不起,如果我不够清楚。我认为你对我的路线是正确的,我会改变这一点。 – user2759575

+0

so ...'@ question.post.questions.order(:created_at).last(2)'。可能甚至想要将'@ post'作为实例变量在视图中使用?所以...'@post = @ question.post'。然后'@ post.questions'等 – Dudo

0

有一个错字。要初始化@comment秒,但使用@comment

def index 
    @question = Question.find params[:question_id] 
    @comments = @question.comments 
    @questions = @comments.collect{|c|c.questions.order(:created_at).limit(2).reverse_order} 
end 

因为评论是一个集合,你会想从每个评论

+0

嗯,这似乎并没有显示任何东西。 – user2759575

相关问题