# How to reorder rows in a table?

**URL:** <https://www.ruby-forum.com/t/how-to-reorder-rows-in-a-table/53547>\
**Category:** Rails\
**Created:** [February 9, 2006, 2:35am UTC](https://www.ruby-forum.com/t/how-to-reorder-rows-in-a-table/53547 "2006-02-09T02:35:44Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Human\_D](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/h/edb3f5/32.png) [@Human\_D](https://www.ruby-forum.com/u/Human_D)\
**Post date:** [February 9, 2006, 2:35am UTC](https://www.ruby-forum.com/t/how-to-reorder-rows-in-a-table/53547/1 "2006-02-09T02:35:44Z")

</div>

Hi,  
I have a link table with a location field, here is the code I wrote to  
reorder the rows

# move\_up action in links controller

def move\_up  
current\_link = Link.find(params[:id])  
current\_link.location -= 1  
current\_link.save

```
same_link = Link.find_by_location(current_link.location)
same_link.location += 1
same_link.save

redirect_to :action => 'list'

```

end

But it does not work always, can’t figure it out.  
What may be the problem?  
Is there a better way to do this?

Thanks

---

<div class="post-metadata">

**Author:** ![Human\_D](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/h/edb3f5/32.png) [@Human\_D](https://www.ruby-forum.com/u/Human_D)\
**Post date:** [February 9, 2006, 2:56am UTC](https://www.ruby-forum.com/t/how-to-reorder-rows-in-a-table/53547/2 "2006-02-09T02:56:00Z")

</div>

When you change current\_link.location in this way, you are potentially  
creating a situation where two records have the same location. Then you  
search by the same value, so you’ll find one of the two with that  
location.  
If you’re unlucky, you’ll find the one you just changed, and will just  
be  
setting it back to its original value again.

I suggest looking at AWDR, p. 254, which describes acts\_as\_list and  
position. Just another reason why I love Rails!

///ark

From: “Human D.” [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid)

Hi,  
I have a link table with a location field, here is the code I wrote to  
reorder the rows

# move\_up action in links controller

def move\_up  
current\_link = Link.find(params[:id])  
current\_link.location -= 1  
current\_link.save

```
same_link = Link.find_by_location(current_link.location)
same_link.location += 1
same_link.save

redirect_to :action => 'list'

```

end

But it does not work always, can’t figure it out.  
What may be the problem?  
Is there a better way to do this?

Thanks

* * *

Rails mailing list  
removed\_email\_address@domain.invalid  
[http://lists.rubyonrails.org/mailman/listinfo/rails](http://lists.rubyonrails.org/mailman/listinfo/rails)
