Home Rails - destroy associations from object with condition
Reply: 0

Rails - destroy associations from object with condition

user838
1#
user838 Published in April 26, 2018, 7:53 am

I have an object @foo with a :has_many associations to bar and I want before foo is destroyed all association objects from bar will be destroyed too if the bar has the property type = test.

the following code is working and the foo object is deleted but the bars are still there: (if I dont't use the condition .where(type: "test) all bars will be deleted)

  def destroy
    @foo.bars.each{|b| b.update_attribute(:blub_id, nil)}
    @foo.bars.where(type: "test").destroy_all
    @foo.destroy
    respond_to do |format|
      format.html { redirect_to foo_url, notice: 'Foo was successfully destroyed.' }
      format.json { head :no_content }
    end
  end
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.306426 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO