如何修改has ::many relationship

时间:2016-07-29 18:46:31

标签: ruby-on-rails associations rails-activerecord

我有一个名为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方法,以便它只选择正确的关联记录?

1 个答案:

答案 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) }