ruby on rails - Use find to select attributes from joined tables -


i have 3 tables,

questionsets

  • has_many :questions

question

  • has_many :answers

answers

now answers table has column called "actual_answer"

now wanted find can answers actual_answers equal specific value , belongs specific question_set.

i have right now:

@questionset= questionset.find(params[:id]) @answers = answer.find(:all, :conditions => ["actual_answer=?", someactualanswer]) answers_i_need = [] @answers.each |answer|   if answer.question.question_set_id == @questionset.id    answers_i_need << answer   end end 

is there better way of doing this, i'm expecting thousand array results , making loop might not perfect way of doing it.

thanks!

why not use has_many ... :through relation? link to: guides

this way can have:

questionset   has_many :questions   has_many :answers, through: :questions  question   has_many :answers   belongs_to :question_set  answer   belongs_to :question 

then in controller have:

@questionset= questionset.find(params[:id]) answers_i_need = @questionset.answers.where('actual_answer = ?', your_actual_value) 

oh, , if have more thousand results query, might consider having @ this.


Comments

Popular posts from this blog

c++ - OpenCV Error: Assertion failed <scn == 3 ::scn == 4> in unknown function, -

php - render data via PDO::FETCH_FUNC vs loop -

The canvas has been tainted by cross-origin data in chrome only -