1

我有模型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

我现在真的不是什么问题,我是不是错误地指定了什么?

4

2 回答 2

1

如果它是 has_and_belongs_to_many :users 和 join_table 是 users_roles 在角色表中的这种情况下,看起来关联存在问题,它也应该是 has_and_belongs_to_many :roles,join_table: :users_roles,这将建立 HABM 关系。

于 2018-06-19T14:56:41.520 回答
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

于 2018-06-21T06:32:50.353 回答