Rails - 从具有条件

时间:2018-01-13 00:12:39

标签: ruby-on-rails ruby ruby-on-rails-4

我有一个对象@foo,其中包含:bar的has_many关联,我希望在foo被销毁之前bar中的所有关联对象也将被销毁{} {1}}具有属性bar

以下代码正常运行且type = test对象已删除,但foo仍然存在: (如果我不使用条件bars,则将删除所有.where(type: "test)

bars

3 个答案:

答案 0 :(得分:3)

不知道这是一个整体规则还是只是针对该控制器的行为,但我认为在模型上做这件事会更好。

不知道究竟是什么行

@foo.bars.each{|b| b.update_attribute(:blub_id, nil)}

确实如此,但是如果blub_id是外键,那么你应该在破坏测试类型的条形图之后这样做。在你的foo模型上,你可以这样做:

before_destroy :destroy_test_bars

def destroy_test_bars
   self.bars.where(type: "test").destroy_all
   self.bars.update_all(blub_id: nil)
end

然后,在您的控制器上,它只是

  def destroy
    @foo.destroy
    respond_to do |format|
      format.html { redirect_to foo_url, notice: 'Foo was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

认为它可行。祝你好运!

答案 1 :(得分:1)

只需删除@foo.bars.each{|b| b.update_attribute(:blub_id, nil)}然后再试一次。我认为blub_id是一个外键,表示当前栏所属的foo。

blub_id等于null时,blub_id null的记录不属于任何内容,然后@foo.bars.where(type: "test").destroy_all不包含这些小节。

答案 2 :(得分:0)

其中一个好方法是添加after_destroy回调,你可以在其中编写任何你想要的逻辑。

class Foo < ActiveRecord::Base
  has_many :bars
  after_destroy :cleanup

  private
  def cleanup
    if self.bars.where(type: "test")
      self.bars.destroy_all
    end
  end
end