0

I have an object Guess and did

y guess = Guess.find_by_id(5)

and got this

id: "5"
firstanswer_chambersapp: f
firstanswer_interview: f
firstanswer_letter: f
firstanswer_drafting: f
firstanswer_barrister: f
firstanswer_solicitor: t
secondanswer_chambersapp: "6"
secondanswer_interview: "2"
secondanswer_letter: "3"
secondanswer_drafting: "5"
secondanswer_barrister: "4"
secondanswer_solicitor: "1"

What I want to do is get all the secondanswers_ and sort them by the integer value (ASC). Is there a way I can do that in ruby/rails?

I'm expecting it to involve

guess.each do |e|

 end

but I'm lost as to the code in the middle :(

Any hints would be helpful. I could also obviously retrieve all results at once

y guess = Guess.all

If that makes them any easier to sort

I'm also wondering if I set the database up the wrong way to make it practical to retrieve the values..

1 Answer 1

1
Guess.select(Guess.column_names.select{|field| field =~ /^secondanswer_/}).find(5)

That will return only the secondanswer_* fields for the record.

Guess.select(Guess.column_names.select{|field| field =~ /^secondanswer_/}).sort{|a,b| a.secondanswer_champbersapp <=> b.secondanswer_chambersapp}

Would return all Guess records sorted by secondanswer_chambersapp.

Sign up to request clarification or add additional context in comments.

1 Comment

thank you . I can read it, but I never would have been able to figure that out, and I'm having trouble implementing it. <br/> I got an unexpected token error in the console when I did: Guess.select(Guess.column_names.select{|field| field =~ /^secondanswer_/}).sort{|a,b| a.secondanswer_champbersapp <=> b.secondanswer_chambersapp} and got an unexpected token "("

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.