如何用has_many摧毁......

时间:2018-02-02 05:36:02

标签: ruby-on-rails ruby rails-activerecord has-many belongs-to

有模型:member(id,project_id,user_id),project(id),user(id),somemodel(id,project_id,user_id)。

  • 成员belongs_to:project,belongs_to:user

  • somemodel belongs_to:project,belongs_to:user

我希望删除成员时删除somemodel(其中project_id和user_id与该成员相同)也会被删除。怎么做?

为此,我希望将 /** * Run the migrations. * * @return void */ public function up() { /** * Drop column type in products table */ Schema::table('products', function (Blueprint $table) { $table->dropColumn('type'); }); /** * Create column product_type in products table */ Schema::table('products', function (Blueprint $table) { $table->integer('product_type_id')->unsigned()->after('price'); $table->foreign('product_type_id')->references('id')->on('product_types')->onDelete('cascade'); }); } /** * Reverse the migrations. * * @return void */ public function down() { /** * Drop column product_type_id in products table */ Schema::table('products', function (Blueprint $table) { $table->dropForeign('product_type_id'); $table->dropColumn('product_type_id'); }); /** * Re-create column type in products table */ Schema::table('products', function (Blueprint $table) { $table->string('type')->after('price'); }); } 添加到成员中,但我不知道在成员类中提供has_many :somemodels, dependent: :destroy的正确参数。仅has_many :somemodels单独尝试通过member_id搜索somemodel时没有工作,而some_odels表中不存在,因此发生has_many :somemodels, dependent: :destroy错误。

no column添加到会员中的权利是什么?

2 个答案:

答案 0 :(得分:1)

另一种方法是为此特定关系创建:through关联,然后将其设置为dependent: :destroy。我认为它的结构如下:

class Member < ActiveRecord::Base

  belongs_to :user
  belongs_to :project

  has_many :some_models, ->(member) { where(user_id: member.user_id) },
                         through: :project,
                         dependent: :destroy
end

我还没有对它进行过测试,但就我所见,这似乎是正确的。

答案 1 :(得分:0)

我认为你应该向Member模型添加一个after_destroy回调:

# In member model
class Member < ApplicationRecord
    after_destroy :also_destroy_somemodel
    ...

   def also_destroy_somemodel
       # Fast, use in case somemodel dont have any callbacks
       Somemodel.where(project_id: project_id, user_id: user_id).delete_all

       # Or
       # Slow, use in case somemodel has callback(s)
       # Somemodel.where(project_id: project_id, user_id: user_id).each &:destroy
   end
end

希望它有所帮助。