Updating a relationship in a has_many and belongs_to


#1

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