title: Grails addTo in for loop
body: <p>I'm doing a website for reading stories. My goal is to do save the content of the story into several pages to get a list and then paginate it easily; I did the following:</p>
  
  <p>In the domain I created two domains, <code>Story</code>:</p>
  
  <pre><code>class Story {
  
      String title
  
      List pages
  
      static hasMany=[users:User,pages:Page]
      static belongsTo = [User]
  
      static mapping={
          users lazy:false
          pages lazy:false
  
      }
  }
  </code></pre>
  
  <p>And <code>Page</code>:</p>
  
  <pre><code>class Page {
      String Content
      Story story
      static belongsTo = Story
      static constraints = {
          content(blank:false,size:3..300000)
      }
  
  }
  </code></pre>
  
  <p>The controller <code>save</code> action is:</p>
  
  <pre><code>def save = {
      def storyInstance = new Story(params)
      def pages = new Page(params)
      String content = pages.content
      String[] contentArr = content.split("\r\n")
  
      int i=0
  
      StringBuilder page = new StringBuilder()
      for(StringBuilder line:contentArr){
          i++
          page.append(line+"\r\n")
  
          if(i%10==0){
  
                 pages.content = page
                 storyInstance.addToPages(pages)
                 page =new StringBuilder()
          }
      }
  
      if (storyInstance.save(flush:true)) {
          flash.message = "${message(code: 'default.created.message', args: [message(code: 'story.label', default: 'Story'), storyInstance.id])}"
          redirect(action: "viewstory", id: storyInstance.id)
      }else {
          render(view: "create", model: [storyInstance: storyInstance])
      }
  }
  </code></pre>
  
  <p>(I know it looks messy but it's a prototype)</p>
  
  <p>The problem is that I'm waiting for <code>storyInstance.addToPages(pages)</code> to add to the set of pages an instance of the pages every time the condition is true. But what actually happens that it gives me the last instance only with the last <code>page_idx</code>. I thought it would save the pages one by one so I could get a list of pages to every story.</p>
  
  <p>Why does this happen and is there a simpler way to do it than what i did?</p>
  
  <p>Any help is appreciated.</p>