Sorting objects without an explicit find function...?

Hello -

I’m kind of new to Rails, and although I can usually google the answer
to whatever problem I’m having, I’m just not sure how to phrase this, so
I come to you all for help.

I’m building an educational app, which (among other things) administers
multiple-choice tests to students. I’m staying RESTful, so Test has_many
Questions and Question has_many Answers. I started by scaffolding those
three, then scrapped all the Question and Answer views. They’re included
in the Test “show” view, which looks roughly like this:


<% for question in @test.questions %>

(question text)

<% for answer in question.answers %>

(text for each answer choice)

<% end %>

<% end %>


So, I’ve gotten that to work just fine. Now I’m trying to make both the
questions and answers each drag-and-drop sortable, so that questions in
a test can be rearranged, and answers in a question rearranged (the
latter seems unnecessary and kind of difficult, but I’m trying to work
it out in order to challenge myself). I’m following Railscast #147 for
this.

So I have almost everything set up - I’ve added the “position” integer
to the questions and answers, and the sort function that updates their
positions in the database after the drag-and-drop is complete. I’ve
confirmed that those are working.

My problem is that when I’m displaying questions and answers, I don’t
know how to make Rails order them using their positions. On a hunch, I
tried changing the view to look like:

<% for question in @test.questions(:order => “position”) %>

<% for answer in question.answers(:order => “position”) %>

That doesn’t give an error, but it doesn’t work either. So, I’m kind of
at a loss about how to do this. I could do it the way the Railscast does
it, and go into the Test controller and Show action and make:

@questions = Question.all(:order => “position”)

And change the view accordingly, but I wouldn’t be able to fix the
answers the same way. There must be some kind of Rails Way that I’m
missing? Or some bit of syntax?

Thoughts? Thank you!

On Feb 17, 6:47 am, Chris H. [email protected]
wrote:

That doesn’t give an error, but it doesn’t work either. So, I’m kind of
at a loss about how to do this. I could do it the way the Railscast does
it, and go into the Test controller and Show action and make:

@questions = Question.all(:order => “position”)

And change the view accordingly, but I wouldn’t be able to fix the
answers the same way. There must be some kind of Rails Way that I’m
missing? Or some bit of syntax?

well you can do question.answers.find(…) if you want, that find will
be scoped to the association. or you can add the condition to the
association itself, ie

class Question
has_many :answers, :order => ‘position’
end

Fred

Ah, that did it. Thank you!