I'm trying to update user permissions using simple_form. When the form loads the currently values are selected correctly. But when making changes those changes are not persisted to the database. I'm using app_ids to assign the permissions. If I do the same in the rails console it seems to work fine.
u = User.find 3
u. app_ids = [1,3,4]
u.save
# create the user_subscriptions
def update
@user = User.find(params[:id])
# binding.pry
authorize @user
if @user.update_attributes(user_params)
flash[:notice] = "Details for #{@user.name} updated."
redirect_to users_path
else
render :edit
end
end
def user_params
params.require(:user).permit(:name, :role, :app_tokens, :provider, :uid, :app_ids)
end
= simple_form_for(user, html: { class: 'form-horizontal' }) do |form|
.form-group.full-name.pull-left
= form.label "Full Name"
= form.text_field :name, placeholder: "Enter name", class: "form-control"
= hidden_field_tag "uid", user.id
p
= form.label "User Level"
.btn-group.user-level.pull-left[data-toggle="buttons-radio"]
= form.input :role, collection: User.roles, as: :radio_buttons, item_wrapper_class: 'btn btn-default', checked: User.roles[user.role], required: true
.form-group
.btn-group.btn-group-lg.app-access data-toggle="buttons"
= form.input :app_ids, collection: App.order(:name), as: :check_boxes, item_wrapper_class: 'btn btn-default'
.text-center.edit-user-submit.actions
= link_to "Cancel", users_path, class: "btn btn-primary btn-sm pull-right"
= form.button :submit, "Save Changes", data: {disable_with: "Updating ..."}, class: "btn btn-default btn-sm pull-right"
class User < ActiveRecord::Base
has_many :user_subscriptions, dependent: :delete_all
has_many :apps, through: :user_subscriptions
after_save :update_apps_access
devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :omniauthable
attr_reader :app_tokens
enum role: [:super_admin, :admin, :generic]
self.per_page = 10
def app_tokens=(ids)
self.app_ids = ids.split(',')
end
def role=(value)
if value.is_a?(String) && value.to_i.to_s == value
super value.to_i
else
super value
end
end
def update_apps_access
return unless role == 'admin' || role == 'super_admin'
App.all.find_each { |app| user_subscriptions.find_or_create_by(app_id: app.id) }
end
def self.from_omniauth(access_token)
data = access_token.info
user = User.find_by(email: data['email'])
user = User.create(
name: data['name'],
email: data['email'],
oauth_token: access_token['credentials']['token'],
uid: access_token['uid'],
provider: access_token['provider']
) unless user
user
end
end
class UserSubscription < ActiveRecord::Base
belongs_to :user
belongs_to :app
end
As there are multiple ids you need to permit the array like this:
def user_params
params.require(:user).permit(:name, :role, :app_tokens, :provider, :uid, app_ids: [])
end