2013-12-12 51 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

相關問題