已审核:与HMABT关系的关联审核

时间:2018-06-19 11:45:45

标签: ruby-on-rails ruby rolify acts-as-audited

我有模型userrole

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

当我创建一个新角色时,出现错误:

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

我现在真的不是什么问题了,我是否错误指定了某些内容?

2 个答案:

答案 0 :(得分:1)

如果在角色表中是has_and_belongs_to_many:users和join_table是users_roles,则关联存在问题,它也应该是has_and_belongs_to_many:roles,join_table::users_roles,这将产生HABM关系。

答案 1 :(得分:1)

我已通过本教程解决了该问题: http://blog.flatironschool.com/why-you-dont-need-has-and-belongs-to-many/

我所做的是删除了HABTM关系并为联接表创建了模型。

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

现在在UsersRole实例上创建带有更改的审计时。 问题在于,更改仅包含已破坏列的ids,因此您无法弄清楚它是什么。 该问题已在此处部分解决:https://github.com/collectiveidea/audited/issues/72#issuecomment-398756380