I have a pretty simple application for assigning Abilitiesto Users, using Permissionsas a connection table. I have included model definitions below.
However Abilitiesalso belongs Client. The form for adding opportunities for the user contains only the "Abilities" for a particular client .
Since the form only returns checked object_properties for this client, if I just use
@user.update(params[:user].permit({:ability_ids => []}))
with form
= simple_form_for(@user, url: user_permissions_path, method: :patch do |f|
= f.hidden_field :client_id, value: @client.id, name: :client_id
= f.association :abilities, as: :check_boxes, collection: @client.abilities
Then, all permissions for all other client applications are removed for that user. This is the controller update code that I am currently using, but I’m sure that I need more “Rails” for this.
update_abilities = params[:user][:ability_ids].reject { |c| c.empty? }
current_abilities = @user.abilities.for_client(@client).pluck(:id).collect{ |i| i.to_s }
abilities_for_deletion = @user.permissions.where(ability_id: current_abilities - update_abilities)
abilities_for_deletion.delete_all unless abilities_for_deletion.empty?
abilities_for_addition = Ability.find(update_abilities - current_abilities)
@user.abilities.push(abilities_for_addition)
class User < ActiveRecord::Base
has_many :permissions, dependent: :destroy
has_many :abilities, through: :permissions do
def for_client(client)
where('abilities.client_id' => client.id)
end
end
end
class Permission < ActiveRecord::Base
belongs_to :ability
belongs_to :user
end
class Ability < ActiveRecord::Base
has_many :permissions, dependent: :destroy
belongs_to :client
end
, , , .
.