SitePoint Sponsor

User Tag List

Results 1 to 4 of 4

Hybrid View

  1. #1
    SitePoint Member
    Join Date
    May 2007
    Posts
    22
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Deleting records with children

    If I delete an object that has child objects, does rails automatically delete them as well or do I need to do it?

    Say I have a model called Project and a model called Article. Project has_many articles and Article belongs_to a project. I can create a new article, but it only exists in the context of a project. Here is the destroy action from my ProjectController:

    Code:
      def destroy
        @project = Project.find(params[:id])
        @project.destroy
    
        respond_to do |format|
          format.html { redirect_to project_url }
          format.xml  { head :ok }
        end
      end
    Should I add something in there that loops through all the child articles and deletes each one? If so, I'd guess that I would call a method in my model called something like kill_articles and pass it as an argument all the child articles. Any suggestions?

  2. #2
    SitePoint Guru silver trophy Luke Redpath's Avatar
    Join Date
    Mar 2003
    Location
    London
    Posts
    794
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    By default, no, Rails won't delete the children automatically. There is however a feature to do just that.

    Code:
    class Project
      has_many :articles, :dependent => :destroy
    end
    This will destroy all associated articles by calling the article's own destroy method. There are other options for :dependent - :delete_all also deletes all associated articles but does it with one SQL statement rather than calling article.destroy which means any destroy callbacks in your Article class will not be called. On the plus side its quicker. Finally you can use :nullify which will set the foreign key (project_id) of each article to null instead of deleting the records.

  3. #3
    SitePoint Member
    Join Date
    May 2007
    Posts
    22
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    That's just what I was looking for -- thanks!

    It sounds like :delete_all is the better way to go unless for some reason I want or need to call each article's destroy action.

  4. #4
    SitePoint Enthusiast
    Join Date
    Jan 2004
    Location
    USA
    Posts
    82
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Yep, exactly. If you have a special destroy action you would not use :delete_all.


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •