2016-04-07 9 views
0

私はRailsで質疑応答アプリケーションを作成しています。すべての質問をリストアップしたページを作成し、直下にその質問の最後の答えを表示するにはどうすればよいですか?テーブル全体を反復し、Railsで各オブジェクトの最後の要素を取得します

これは私の答えコントローラです:

class AnswersController < ApplicationController 
    def index 
     @questions = Question.all 
    end 
end 

質問と答えモデル:

Indexビュー
class Answer < ActiveRecord::Base 
    belongs_to :question 
end 

class Question < ActiveRecord::Base 
    has_many :answers, dependent: :destroy 
end 

:私が表示されるタイトルを得たが、取得することはできません

<% if @questions.blank? %> 
    <p>No questions to display</p> 
<% else %> 
    <% @questions.each do |question| %> 
     <h2><%= question.title %></h2> 
     <!-- This is where the answer should appear. 
     It should be the last answer in the question. --> 
    <% end %> 
<% end %> 

体が働く。

悪いタイトルで申し訳ありませんが、私はタイトルに「質問」と書くことができませんでした。

ありがとうございました!

答えて

1

あなたはthis-

<% if @questions.blank? %> 
    <p>No questions to display</p> 
<% else %> 
    <% @questions.each do |question| %> 
    <h2><%= question.title %></h2> 
    <!-- This is where the answer should appear. 
    It should be the last answer in the question. --> 
    <%= question.answers.last %> 
    <% end %> 
<% end %> 
+0

を試すことができありがとうございましたが、それはうまくいきませんでした。それは私にこのエラーを与える:SQLite3 :: SQLException:いいえそのような列:answers.question_id:SELECT "answers"。* FROM "answers" WHERE "answers"。 "question_id" =? ORDER BY "answers"。 "id" DESC LIMIT 1 –

+0

テーブル 'answers'に' question_id'の外部キーがありますか? – dp7

+0

はい!それが問題でした。私はすでに参照なしで移行を生成していました。どうもありがとう!返事が遅れて申し訳ありません。 –

関連する問題