0

I am building a multiple choice survey with a set of fixed questions and fixed answers. A question has_many answers and an answer belongs_to question. The questions and answers will be seed data in the db and will be written in the seeds.rb file.

I am trying to figure out how to relate the surveys to the questions and answers. Users can pick from taking a short or long survey, each of which will have a different amount of questions. So a survey needs to be able to keep track of which questions it has, and the answers chosen for each question. I've started out with this relationship for surveys and questions:

class Survey < ActiveRecord::Base
    has_and_belongs_to_many :questions
end  

class Question < ActiveRecord::Base
    has_and_belongs_to_many :surveys
end  

Now I can't figure out how to put answers into this. A question has_many :answers, but how do i relate the answers to surveys? I was thinking a has_many through relationship, but I can't see how that would work.

Any ideas?

Philip7899
  • 4,599
  • 4
  • 55
  • 114

1 Answers1

0
class Survey < ActiveRecord::Base
    has_many :questions
end  

class Question < ActiveRecord::Base
    has_many :answers
    belongs_to: survey
end  

class Answer < ActiveRecord::Base
    belongs_to :question
end

Suppose, for any specific survey,

Survey.find(1).questions.collect{|x| x.answers}

In this way you can find an array of arrays which contains each question with answers. I guess this is what you need.

Emu
  • 5,763
  • 3
  • 31
  • 51
  • Thanks, but this doesn't work, because it requires a new instance of question to be created for each survey. This won't be efficient as the questions are always the same. All the questions and answers exist once as they are created in the seeds.rb file. I somehow need to relate the survey to both questions and answers. I'm somewhat sure that my method of relating surveys to questions is solid, but not I can't figure out how to get answers correctly – Philip7899 Feb 12 '15 at 18:26