# Updating a relationship in a has\_many and belongs\_to

**URL:** <https://www.ruby-forum.com/t/updating-a-relationship-in-a-has-many-and-belongs-to/57211>\
**Category:** Rails\
**Created:** [April 7, 2006, 11:29pm UTC](https://www.ruby-forum.com/t/updating-a-relationship-in-a-has-many-and-belongs-to/57211 "2006-04-07T23:29:53Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![alex](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/db5fbb/32.png) [@alex](https://www.ruby-forum.com/u/alex)\
**Post date:** [April 7, 2006, 11:29pm UTC](https://www.ruby-forum.com/t/updating-a-relationship-in-a-has-many-and-belongs-to/57211/1 "2006-04-07T23:29:53Z")

</div>

As the subjects suggests I’m trying to reiterate through certain pages,  
assigning them to certain menus. My code is as follows

When I run the Below the position updates fine, but the menu\_id in Page  
doesn’t seem to change it all.  
params[“group\_#{params[:id]}”].each\_with\_index do |id, position|  
Page.update(id, :position =\> position + 1, :menu =\> menu)  
end

When I run the Below it sometimes works but always says: You have a nil  
object when you didn’t expect it!The error occured while evaluating  
nil.each\_hash

params[“group\_#{params[:id]}”].each\_with\_index do |id, position|  
@page = Page.find(id)  
@page.position = position + 1  
@page.save!  
@page = nil  
Page.find\_by\_sql([“UPDATE pages SET menu\_id = ? WHERE id =  
?;”,params[:id], id])  
end

Basically what I need is either a way to actually save the new menu  
relationship, which isn’t happening in the first example, or to edit the  
‘menu\_id’ manually with sql. How can I access the SQL directly in rails  
(without find\_by\_sql)?
