0

I have a really basic model relationship of has_and_belongs_to_many, through: 'table_name'

Which we can see here:

Roles

module Xaaron
  class Role < ActiveRecord::Base
    extend FriendlyId
    friendly_id :role, use: [:slugged, :history]
    has_and_belongs_to_many :permissions, join_table: 'permissions_roles'

    validates :role, presence: true
    validates_uniqueness_of :role

    def has_permission?(permission_name)
      permissions.where(permission: permission_name).any?
    end

    def permission_names=(names)
      names.each do |name|
        permission = Xaaron::Permission.where(permission: name)
        if permission
          self.permissions = permission
        end
      end
    end
   end
 end

Permissions

module Xaaron
  class Permission < ActiveRecord::Base
    extend FriendlyId
    friendly_id :permission, use: [:slugged, :history]

    validates :permission, presence: true, uniqueness: true
  end
end

The issue I am having is the roles permission_names, I can pass in an array of names: ['can_create', 'can_edit', 'can_delete'] and it will check if they exist. How ever it will only add one to the join table, it will the over write that one with the next one and then the last one, resulting in the relationship only showing one permission for one role, when it should be three permissions for one role.

So I opened up rails c and did the following:

@role.permissions.create(permission: 'example')

I found that by going directly through this type of chaining, I could create multiple permissions for a role. I don't want to create multiple permissions on the fly for a role. I want to assign permissions to a role that already exist, and either assign one or assign 100 and have them all show up.

What do i have to do, to be able to do, @role.permission_names(['perm1', 'perm2', ...]), and have it assign all the permissions to that role, if they exist?

user3379926
  • 3,855
  • 6
  • 24
  • 42

1 Answers1

1

Your permission_names= method definition is the problem. In it, you keep setting self.permissions to an array with a single element.

Try this instead.

def permission_names=(names)
  self.permissions = Xaaron::Permission.where(name: names)
end
Mark Przepiora
  • 171
  • 1
  • 3