lundi 12 décembre 2016

Rails: how to update HABTM checkbox value

I am following railscast 17-- HABTM checkbox to add attribute to my user model.

   <%= hidden_field_tag 'user[role_group_ids][]',nil %>
     <%  RoleGroup.all.each do |role_group|%>
     <%= check_box_tag 'user[role_group_ids][]',role_group.id,
       @user.role_group_ids.include?(role_group.id) %>
     <%= role_group.name %><br>
   <% end %>

In the update action, if I update all attributes like this, everything is ok.

  def edit
   @user = User.find(params[:id])
   @user.update(user_params)  # user_params is strong parameter
  end

  def user_params
    params.require(:user).permit(:username, :password, :password_confirmation, role_group_ids:[])
  end

But I just want to update the value of checkboxes instead of all attributes, I tried this, however it did not work.

  def edit
    @user.update_attribute(:role_group_ids, user[role_group_ids])
  end

Anybody could tell me how to fix this?




Aucun commentaire:

Enregistrer un commentaire