1

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
1
  • is this really your code? def edit @task = Task.find(params[:id],:order=>'position') end Commented Feb 17, 2011 at 21:23

4 Answers 4

1

I changed the model to

class User < ActiveRecord::Base
     has_many :tasks, :order=>'position'
end
Sign up to request clarification or add additional context in comments.

Comments

1

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 Comment

changing my model to your suggestion somehow breaks the has_attached_file on the user. Not sure why.
1

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.

2 Comments

Are you suggesting .order(:position) in the view??
in the view, or you could make a scope for it.
1

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')

Comments

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.