Skip to content

add_role could be better optimized #558

Open

Description

@MatthewSuttles

We currently use Rolify in our application. Adding a role for a user was getting very slow and would break for most of our clients.

Doing some investigation I found the add method was doing this.

def add(relation, role) relation.roles << role unless relation.roles.include?(role) end

The includes seems to be loading ever record.
Cursor_and_Terminal_—ruby_bin_rails_c—_143×56

If someone could verify they are seeing the same thing I would really appreciate it. Currently using Rails 5.2.2

Activity

  1. thomas-mcdonald commented on Apr 20, 2021

    @thomas-mcdonald
    Member

    This is unexpected - can you run this with something that will show you location those queries are being generated from? Newer Rails should do it out of the box or something like https://github.com/brunofacca/active-record-query-trace will help

  2. trein-homeroom commented on Jul 29, 2022

    @trein-homeroom

    I've hit this as well. The location is as mentioned above, in the add method, the roles.includes call. It causes all roles to load, rather than having the DB do the work. It should be roles.exists instead.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions