【发布时间】: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: :destroy:project_user_roles这是所有角色的关联...您是否尝试将其删除并将其放在其他两个关联中? -
我尝试将
dependent: :destroy更改为其他关联,但没有效果。
标签: ruby-on-rails where-clause has-many-through