1

I want to retrieve status data from table projects in ror project.

the mysql code will be :

Setect status from projects where id = 2;

Im new to ror so I try use raw mysql to retrieve data:

sta1=Project.find_by_sql(["SELECT status FROM projects WHERE id = ?",id1]).first

This returns a #

I'm expecting a string either "on" or "off"

whats my problem?

4
  • possible duplicate of find_by_sql in Rails, accessing the resulting array Commented Jun 18, 2014 at 4:31
  • 2
    I think you just need ...first.status. Commented Jun 18, 2014 at 4:31
  • 1
    Incidentally, you probably never want to use find_by_sql when there is a 'Rails way' of doing this... sta1 = Project.find(id1).status is where'd you go if you're finding by id... Commented Jun 18, 2014 at 4:48
  • Most (almost all) queries can be written without raw SQL, so consider that thing a last resort. Even if standard ActiveRecord snippets you can find are not enough for you, you can use arel that defines queries similarly to SQL but with possibility to use Ruby in constructing it. Commented Jun 18, 2014 at 12:03

1 Answer 1

0

Use pluck to get a single value out of the record. It returns an array.

http://apidock.com/rails/ActiveRecord/Calculations/pluck

Project.where(id: id1).pluck(:status).first
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.