1
votes

I've got a nice 3-level nested-form using formtastic_cocoon (jquery), and now I want to be able to sort the 2nd set of items in the form.

I've got jQuery ui working no problem, so now to set and update the sort order in rails.

I started following the rails bits of railscasts sortable lists http://asciicasts.com/episodes/147-sortable-lists

The form structure is User->Tasks->Location.

In my Task Model I set index to

 def index
    @task = Task.find(params[:id],:order=>'position')
 end

def edit 
    @task = Task.find(params[:id],:order=>'position')
end 

and I was expecting my console to see

... FROM 'tasks' WHERE ('users'.'id' = 12) ORDER BY ('position')

or something along those lines, but there is no order by output.

Is there somewhere else that I need to define this order?? Where does the nested_object get its relationship from? The model only?

My models are

class User < ActiveRecord::Base

     has_many :tasks
end 

class Task < ActiveRecord::Base

    belongs_to :user
end
4
is this really your code? def edit @task = Task.find(params[:id],:order=>'position') end stef

4 Answers

1
votes

I changed the model to

class User < ActiveRecord::Base
     has_many :tasks, :order=>'position'
end
1
votes

You are using the wrong model, that id is of a user, so you have to do:

User.find(params[:id]).tasks(:order => 'position ASC')

Otherwise you are just getting the task with id = 12 and not the tasks whose user_id = 12

1
votes

From the answer that you've given, I suspect the real issue lies not in the tasks controller. The default order you gave is great, but if you had some other order or filter requirements, the tasks model won't quite do it either.

I suspect you were actually in users#edit, or possibly a _form.html.erb, where it displays the form elements for each task. There might have been a @user.tasks.each {...} or similar loop block.

For a given user then, do: @user.tasks.order(:position). Or maybe you need open tasks: @user.tasks.where(:open=>true) etc.

1
votes

Your code is slightly wrong here.

To find that user's tasks you would do this in your route:

User.find(params[:id]).tasks(:order=>'position')