Rails how to return a list of answers with a specific question_id
Posted
by
mytwocentsisworthtwocents
on Stack Overflow
See other posts from Stack Overflow
or by mytwocentsisworthtwocents
Published on 2012-10-09T21:12:19Z
Indexed on
2012/10/09
21:38 UTC
Read the original article
Hit count: 152
Let's say I have two Models, Answers and Questions (there are others, but irrelevant to the question). The models are as follows:
Answer.rb
class Answer < ActiveRecord::Base
attr_accessible :description, :question_id
has_one :question, :through => :user, :dependent => :destroy
validates :description, :presence => true
end
Question.rb
class Question < ActiveRecord::Base
attr_accessible :budget, :description, :headline, :user_id, :updated_at, :created_at
belongs_to :user
has_many :answers
validates :headline, :description, :user_id, :presence => true
end
I'd like to display on a page a list of all answers associated with a question, and only those questions.
I got this far. I believe this variable finds all the questions in the database by the question_id (foreign key):
@findanswers = Answer.all(params[:question_id])
And this one grabs the the id of the current question (this code will reside as an ERB on the page where the current question is located):
@questionshow = Question.find(params[:id])
And now I'm stuck. How do I put the two together so that I list all the answers with the current question id?
© Stack Overflow or respective owner