我有一个名为Family
的模型,它与has_many
的关系Parent
:
class Family < ActiveRecord::Base
has_many :parents, :dependent => :destroy
end
当用户删除Family
时,它应删除任何关联的Parent
。
有一个主要障碍:我有一个多租户环境(使用Apartment gem),父母都在公共架构中。因此,我只需要选择父母在同一帐户中应该删除。
现在,当Family
调用destroy时,我得到:
SELECT "public"."users".* FROM "public"."users" WHERE "public"."users"."type" IN ('Parent') AND "public"."users"."family_id" = $FAMILY_ID
我需要它:
SELECT "public"."users".* FROM "public"."users" WHERE "public"."users"."type" IN ('Parent') AND "public"."users"."family_id" = $FAMILY_ID AND "public"."users"."account_id" = $CURRENT_ACCOUNT_ID
有没有办法覆盖Family.destroy
方法,以便它只选择正确的关联记录?
答案 0 :(得分:0)
这是我选择的解决方案。我从dependent: :destroy
模型中的has_many :parents
关系中删除了family.rb
子句。相反,我在家庭控制器的destroy
操作中执行级联删除:
def destroy
@family = Family.find(params[:id])
authorize @family
parents = @family.parents.for_account(current_account.id)
@family.destroy
if @family.destroyed?
parents.destroy_all
end
redirect_to families_path
end
我必须在控制器中执行此操作,因为控制器在模型不知道的情况下知道current_account
。 Parent模型上的for_account
方法如下所示:
scope :for_account, -> (id) { where(:account_id => id) }