Rajasekar Sankar
Rajasekar Sankar

Reputation: 101

find_by_sql in ruby on rails gives an error

I have to get the value of a column in ruby on rails i use find_by_sql to get the value in mysql-cmd the value returns correctly but in view page it returns a random value

passed_question = params[:passed_question]
@answer.questions_id = passed_question
next_question = params[:next_question]
@question = Question.find_by_id(passed_question)
@module = Question.find_by_sql ["SELECT student_additional_field_id FROM questions WHERE id=#{passed_question}"]

it 127450632 value but in mysql cmd

mysql> select student_additional_field_id from questions
-> where id=3;
+-----------------------------+
| student_additional_field_id |
+-----------------------------+
|                           1 |
+-----------------------------+

thanks in advance

Upvotes: 0

Views: 141

Answers (2)

ScottJShea
ScottJShea

Reputation: 7111

This line:

@module = Question.find_by_sql ["SELECT student_additional_field_id FROM questions WHERE id=#{passed_question}"]

Should probably be:

@module = Question.find_by_sql ["SELECT student_additional_field_id FROM questions WHERE ?", passed_question]

UPDATE:

It would have been nice if I had posted a link to the doc and more explanation. When using variable in the find_by_sql you mark their lace with a ? and then list the variables in order at the end.

Upvotes: 1

Siva
Siva

Reputation: 8058

Because find_by_sql will return an Array

How are you trying to access the value from result ?

have you tried it like this

@module = Question.find_by_sql ["SELECT student_additional_field_id FROM questions WHERE id=#{passed_question}"]

student_additional_field_id = @module[0].student_additional_field_id

Upvotes: 3

Related Questions