views:

31

answers:

1

I just had a quick question as I'm still learning grails. I have a controller class that just reads a text file and loads a list with information. I'm wanting to populate one of my domains through this list. Am I able to do it like this?

For instance, I have a bookController, the controller does something like

//psuedocode
import bookdemo.book

readFile(bookData) into list
int a = list.size

a.times {
    new Book(Author:"$list.author", Title:"$list.title").save()
}

For some reason it doesn't add it to the list. I went ahead and looked through grails but I didn't find anything relevant or I missed it. When I print the list, it's populated. When I print the book it prints out 'bookdemo.book'

My apologies if this is very basic, I'm going to continue digging through grails.org while this question is posted.

A: 

I think whatever readFile returns (a map? a Book?), you need to iterate through the list. What you have doesn't have any way of indexing the list. I don't see what $list.author can resolve to.

Assuming readFile returns a Map I would think something like

list.each { mymap => new Book(mymap).save() }

is in the direction of what you want (though my closure syntax is probably wrong).

Nathan Hughes
My apologies, I did a terrible job explaining. You are correct, it is a map, not a list. (rather, I have a list of maps that I iterate through). I actually just realized I am doing a few things backwards/wrong. I am going to go back and go through it, for now I'll mark your answer as correct. I believe what I need to do is add a button to the generated book controller something like 'populate' that reads my file, iterates through, and adds a new book (instead of trying to do it through a separate controller). Will post back once things are tested. I need to set up a database apparently
StartingGroovy