Search code examples
ruby-on-railsrubyrolifyacts-as-audited

Audited: Associated audits with HABTM relation


I've got model user and role

class User < ApplicationRecord
  rolify strict: true

  has_many :roles, through: :users_roles
  has_associated_audits


class Role < ApplicationRecord
  has_and_belongs_to_many :users, join_table: :users_roles
  audited associated_with: :users, join_table: :users_roles

When I create a new role, I've got the error:

2.4.4 :373 >   User.first.add_role Role.pi, ProjectRequest.find(319)
  User Load (0.7ms)  SELECT  `users`.* FROM `users` ORDER BY `users`.`id` ASC LIMIT 1
  ProjectRequest Load (0.6ms)  SELECT  `project_requests`.* FROM `project_requests` WHERE `project_requests`.`id` = 319 LIMIT 1
  Role Load (0.6ms)  SELECT  `roles`.* FROM `roles` WHERE `roles`.`name` = 'pi' AND `roles`.`resource_type` = 'ProjectRequest' AND `roles`.`resource_id` = 319 ORDER BY `roles`.`id` ASC LIMIT 1
   (0.2ms)  BEGIN
  SQL (0.6ms)  INSERT INTO `roles` (`name`, `resource_type`, `resource_id`, `created_at`, `updated_at`) VALUES ('pi', 'ProjectRequest', 319, '2018-06-19 11:40:13', '2018-06-19 11:40:13')
   (54.3ms)  ROLLBACK
NoMethodError: undefined method `primary_key' for User::ActiveRecord_Associations_CollectknowProxy:Class

I don't really now whats the problem, did I wrongly specified something?


Solution

  • I've resolved the problem by this tutorial: http://blog.flatironschool.com/why-you-dont-need-has-and-belongs-to-many/

    What I did was that I removed the HABTM relation and created model for the joining table.

    class User < ApplicationRecord
      rolify strict: true
      has_many :users_roles
      has_many :roles, through: :users_roles, dependent: :destroy
      has_associated_audits
    
    
    class Role < ApplicationRecord
      has_many :users_roles
      has_many :users, through: :users_roles, dependent: :destroy
      audited associated_with: :users
    
    class UsersRole < ApplicationRecord
      # audited associated_with: :role
      audited associated_with: :user
    
      belongs_to :user
      belongs_to :role
    end
    

    Now when the audits are created with change at the UsersRole instance. The problem is that, the change's contains only the ids of destroyed columns, so you cannot figure, what it was. This problem is partially solved there: https://github.com/collectiveidea/audited/issues/72#issuecomment-398756380