Rails 4 has_many通过where子句删除多个关联

时间:2016-06-07 00:39:07

标签: ruby-on-rails where-clause has-many-through

我有一个项目模型,它为用户提供了各种角色。用户可能具有项目的多个角色。我已经使用has_many through和where子句设置了项目模型关联,以显示角色的类型:

  has_many :project_user_roles, dependent: :destroy

  has_many :sub_contractors,
           -> { where(project_user_roles: {role: 'SubContractor'}) },
           through: :project_user_roles,
           source: :user

  has_many :consultants,
          -> { where(project_user_roles: {role: 'Consultant'}) },
          through: :project_user_roles,
          source: :user

在我的项目控制器中,我可以更新sub_contractor_ids和consultant_ids。这适用于为所有情况添加和删除角色,除非用户既是分包商又是顾问,并且删除了顾问角色。在这种情况下,删除所有角色!传递的参数哈希是正确的:

Parameters: {"utf8"=>"✓", "project"=>{"sub_contractor_ids"=>["3", ""], "consultant_ids"=>[""] ...

,但我可以在控制台中看到update_attributes命令导致SQL:

SQL (0.2ms)  DELETE FROM "project_user_roles" WHERE "project_user_roles"."project_id" = $1 AND "project_user_roles"."user_id" = 3  [["project_id", 3]]

显然没有考虑关联中的where子句,该子句应该将此删除仅限于那些“顾问”的角色。

如上所述,添加角色很好。如果该用户没有角色并且传递了相同的参数:

Parameters: {"utf8"=>"✓", "project"=>{"sub_contractor_ids"=>["3", ""], "consultant_ids"=>[""] ...

生成的SQL包含where子句中的角色:

SQL (0.4ms)  INSERT INTO "project_user_roles" ("role", "project_id", "user_id", "created_at", "updated_at") VALUES ($1, $2, $3, $4, $5) RETURNING "id"  [["role", "SubContractor"], ["project_id", 3], ["user_id", 6], ["created_at", "2016-06-07 00:32:17.224502"], ["updated_at", "2016-06-07 00:32:17.224502"]]

我要么没有正确理解where子句,要么这不是设置它的最佳方法。非常感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

虽然我不能100%确定为什么这样做似乎与我相同,但这就是我现在建立关联的方式:

has_many :consultant_roles,
          -> { where(project_user_roles: {role: 'Consultant'}) },
          class_name: "ProjectUserRole"
has_many :sub_contractor_roles,
          -> { where(project_user_roles: {role: 'SubContractor'}) },
          class_name: "ProjectUserRole"

has_many :main_contractors,
           through: :main_contractor_roles,
           source: :user

has_many :sub_contractors,
           through: :sub_contractor_roles,
           source: :user