Many to many relationship and update problem


#1

I am new to Ruby on Rails. Actually I just started two days ago… I am
working o existing code and having a problem. we have two database
tables called ‘users’ and ‘roles’ they are many-to-many relationship and
linked through mapping table called roles_users. I want to update user’s
role, but I have no idea how to do, primarily because roles are not
inherent members of users. The following is the my code snippet, please
help me out. Please also let me know if you need clarification. Thanks.

Nam

  • Currently, I am assuming that users have two roles, but they can have
    multiple roles. So don’t be confused.

-------------------In
_form.rhtml------------------------------------------

Roles: <%= updating ? collection_select(:role, :id, @roles, "id", "name"): (@user.visible_roles.collect { |role| role.name }.sort.join(", "))%>

-------------------In update action in
‘user_controller.rb’----------------
@user = User.find(params[:id])
@new_role = Role.find(params[:role][:id])
@old_role = @user.visible_roles.collect { |role| role.name
}.sort.join(", ")
@old_role = Role.find_by_name(@old_role)
@user.roles.each_index{|index|
if (@user.roles[index].id == @old_role.id)
@user.roles[index] = @new_role
end
}
prior_approval = @user.approved
#@user.update_attributes({:roles=>@user.roles})
@user.update_attributes(params[:user])


#2

I solved the problem. Yeah I am stupid
Here is the code snippet which solved the problem I had.

  @user.roles.delete(@old_role)

  @user.roles<<@new_role

Nam Kim wrote:

I am new to Ruby on Rails. Actually I just started two days ago… I am
working o existing code and having a problem. we have two database
tables called ‘users’ and ‘roles’ they are many-to-many relationship and
linked through mapping table called roles_users. I want to update user’s
role, but I have no idea how to do, primarily because roles are not
inherent members of users. The following is the my code snippet, please
help me out. Please also let me know if you need clarification. Thanks.

Nam

  • Currently, I am assuming that users have two roles, but they can have
    multiple roles. So don’t be confused.

-------------------In
_form.rhtml------------------------------------------

Roles: <%= updating ? collection_select(:role, :id, @roles, "id", "name"): (@user.visible_roles.collect { |role| role.name }.sort.join(", "))%>

-------------------In update action in
‘user_controller.rb’----------------
@user = User.find(params[:id])
@new_role = Role.find(params[:role][:id])
@old_role = @user.visible_roles.collect { |role| role.name
}.sort.join(", ")
@old_role = Role.find_by_name(@old_role)
@user.roles.each_index{|index|
if (@user.roles[index].id == @old_role.id)
@user.roles[index] = @new_role
end
}
prior_approval = @user.approved
#@user.update_attributes({:roles=>@user.roles})
@user.update_attributes(params[:user])