【问题标题】:Rails 4 has_many through with where clause deletes multiple associationsRails 4 has_many 通过 with where 子句删除多个关联
【发布时间】:2016-10-06 17:37:06
【问题描述】:

我有一个为用户提供各种角色的项目模型。一个用户可能对一个项目有多个角色。我已经使用 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 和 advisor_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 子句,要么这不是设置它的最佳方式。非常感谢任何帮助。

【问题讨论】:

  • 您在主要关联中有dependent: :destroyproject_user_roles 这是所有角色的关联...您是否尝试将其删除并将其放在其他两个关联中?
  • 我尝试将 dependent: :destroy 更改为其他关联,但没有效果。

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


【解决方案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

【讨论】:

    猜你喜欢
    • 2014-12-16
    • 2016-03-20
    • 1970-01-01
    • 2012-07-09
    • 2017-04-23
    • 1970-01-01
    • 2012-05-13
    • 2014-12-12
    • 2015-11-16
    相关资源
    最近更新 更多