开发者

pulling one field of a record into an array in a Rails 3 app

Rails 3 noob here. Currently the code in my controller below is getting the whole record in my database. I am trying to populate the array with one integer, not the whole record. The integer is contained in a table "answers" and the field name is "score". How can i modify this line in my controller to get just the one field?

@questions.each do |s|
   @ans[s.position] = Answer.where("question_id = ? AND user_id = ?", s.q_id, current_user.id )
end

UPDATE FOR CLARIFICATION: The :score can be any开发者_如何学编程 integer from 0 to 5. I would like to populate @ans[s.position] with the integer.

Thanks.


You're very close

@questions.each do |s|
  @ans[s.position] = Answer.where("question_id = ? and user_id = ?",s.q_id,current_user.id).select(:score).first.try(:score)
end

You need to select "score" from Answer, then you need to retrieve it from the object.


Since where could potentially return many Answers, use first to pull off the first Answer, and then score to project out the score field.

answers = Answer.where("question_id = ? AND user_id = ?", s.q_id, current_user.id )
score = answers.first.score

All together it would be:

@questions.each do |s|
   @ans[s.position] = Answer.where("question_id = ? AND user_id = ?", s.q_id, current_user.id ).first.score
end

As an optimization to only retrieve score from the database, instead of answers.*, you could use select(:score).

@questions.each do |s|
   @ans[s.position] = Answer.where("question_id = ? AND user_id = ?", s.q_id, current_user.id ).select(:score).first.score
end

See Active Record Query Interface for more about using select.


Just include them.

@questions = Question.includes(:answers).select(:position)

Or use this

@questions = Question.select(:position)
@questions.each{ |s| @ans[s.position] = s.answers.where(:user_id => current_user.id) }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜