How to create and save data on the go in Grails? - grails

I have 2 domain classes
Expenditure
class Expenditure {
Date date
Supplier supplier
String particular
BigDecimal amount
}
Supplier
class Supplier {
String name
String address
static hasMany = [expenditures: Expenditure]
}
What happening is that when I create a new expenditure, I will enter the supplier from the list of suppliers in the Supplier class. When the supplier is not exist, I will have to create it first and then select it when creating the expenditure.
What I want is that, when I enter the supplier it will be looked up, and when not found, it will be created on the go (when saving the expenditure instance) without me having to create it first in the Supplier table and then come back to Expenditure to complete the form.
How can I achieve this?

What I want is that, when I enter the supplier it will be looked up,
and when not found, it will be created on the go
One option you have is to do something like one of these...
Supplier.findOrCreateByName('some name goes here')
Supplier.findOrCreateByNameAndAddress('some name goes here', 'some address goes here')
There are also findOrSaveBy... counterparts but those only work if you are supplying enough search criteria to create a fully save-able instance.
I hope that helps.

Related

Grails doesn't save domain's field

I have two domain classes
class Country {
... // some fields, including other domains
}
class City {
... // some fields, including other domains
Country itsCountry
}
One of my service method is here:
City createCity(String name, Country country) {
// country is existing and loaded in the controller's layer and passed here
City city = new City()
city.itsCountry = country // it is not persisted
city.save('flush':true)
}
The problem is that in the database the city has null country.
Of course, I simplified the example, really is it more complicated. (Unfortunately, some important details can be lose, I hope if you faced this problem, you share the reason)
What I did without success:
playing with Country, getting it by id inside the service method, save and flush it before saving the City object
make the itsCountry field not nullable. So I got an exception from database, that this field can't be null.
I feel that it must be some trivial thing. What can be a reason of it?
in Grails we can already get the country id in params .Right.
like for example, params?.countryId.
If it is new record for country table, then first create new object for country and assign in city object.
For example,
Country country = new Country()//for new record
country.name=params?.countryName
City city=new City()
city.itsCountry = country
city.save('flush':true)
If you have already country record in table then use get method to get object and assign it to city.
For example,
Country country=Country.get(Long.valueOf(params?.countryId))
city.itsCountry = country
city.save('flush':true)
I hope it will help you. If any doubt please ping me.

Understanding hasMany behavior in grails and how to save a relationship

I'm making a model where a User fills out many questionnaires and the responses get saved to Questionresponse. I'm on grails 2.5.2
Test1
So I have two models
class User {
String username
...
static hasMany = [reponse: QuestionResponse]
}
class QuestionResponse {
String question_1
String question_2
...
}
With the above, a new DB table is created: user_questionresponse with two columns user_questionresponses_id and questionresponse_id. This seems like what I want. A user would have many questionresponses and those relationships would be saved in this table. However, I can't find out how to save data to this table.
For example, if I do:
def user = springSecurityService.currentUser
def questionnaire = new QuestionResponse(question_1: "foo", question_2: "bar")
//How do I link the user to this newly created questionnaire?
user.addToResponse(q).save(flush: true) //DOES NOT WORK.
Test2 (just add belongsTo)
class User {
String username
...
static hasMany = [reponse: QuestionResponse]
}
class QuestionResponse {
String question_1
String question_2
static belongsTo = [user: User]
...
}
If I add belongsTo to QuestionResponse a new column, user_id, gets created in the DB. Now if I run the same code as above, this user_id column has the id populated with that of the current user. However, the relationship table, user_questionresponse is still empty.
I am aware of the approach mentioned by Burt but I assume that should be required only for ManyToMany relationship. If that is required for all relationship, why isn't that the default?
In your first case, you have a OneToMany relationship between User and QuestionResponse with no side being the owner of the relationship. In this case to maintain the relationship between User and QuestionResponse, a third table is required. To persist data you need to do the:
userInstance.addToResponse(new QuestionResponse(question_1: "foo", question_2: "bar")).save(flush: true, failOnError: true)
You are doing user.addToReponse(q) instead it should be user.addToReponse(questionnaire), if it's not a typo and the data is actually not being stored, then check by adding the failOnError parameter to save() method. Sometimes grails save() method fails silently, it should tell you if this is the case.
In second case, you have added the parent to the relationship, so that means you don't need the third table to maintain the relationship. Grails will not create and populate the third table in this case.
The second approach (adding belongsTo in QuestionResponse) seems the right thing to do in your case, since QuestionResponse objects cannot exists without a user and cannot belong to different users.
In that case there's no need to use a third table.
When you run the app for the first time, grails created the relation table (because there was no belongsTo). When you run the app again with belongsTo grails adds the user_id field but DOES NOT DROP the relation table. That's why the table is there and is empty: it's not needed, but grails database auto-update feature only adds things, it does not remove anything.
The same applies to fields: if you remove a field from an entity you have to manually remove it from the database.

Grails relating values from two different domains in a custom view

While I'm experienced with Java, I am a Grails newbie but I am trying to get into it. I set up a basic "School" application containing the following domains:
Student
Class
Attendance
Both the 'Student' and 'Class' domains are scaffolded. Now, I want to create the 'Attendance' domain, and I'm going to need a controller with a custom view. I can do that, I'm just looking to understand (at a high level) the best way to set up the view (let's call it 'attendance.gsp').
The view will contain a dropdown box to select a class. Once a class is selected, I want to populate a table. The first column will contain the list of students in the class, and the second column will contain "Attended?" checkboxes.
I think that I can at least get that far.
I am wondering how to go about relating the checkbox value to the student. Since this class is not scaffolded, no attendance column has been created in the database. Do I need to have anything defined in the Attendance domain? How might you go about doing this? Can anyone recommend a particular example online that is doing something similar?
Thanks!
Something like this:
class Class {
...
static hasMany = [sessionsAttendance: Attendance]
}
class Student {
....
}
class Attendance {
static hasMany = [studentsAttended: Student]
}

django admin foreignKey display troubles

I can't seem to find a solution for the following in the django docs.
So for example, i have a field in Class table called department that points to Department database (foreignKey). If I create a admin interface for Class table called ClassAdmin(admin.ModelAdmin). Then i create an entry for Department class. Now automatically, when i try to create a new Class entry, it will show a dropdown menu for entries in Department. The problem arises when i try to do that, it would show something along the lines of "Department Object" for each entry in the dropdown. I would like a way to define canonical names for each entry for department (Department.name is the field i would like to use).
Does anyone know how to do that?
Thanks a lot!
Implement the __str__ method in your Department model:
def __str__(self):
return self.name

Passing Data Between Views and Controllers

I'm working on an application that manages people and their spouses, if married. Essentially a person will be entered and then from that person I want to be able to add a spouse. My database schema is like this. Persons (Person_ID, Name, BirthDate, etc...), Marriages(Marriage_ID, Husband_ID, Wife_ID, Date).
The process is Add a Person then, if married, add spouse. So I have a Person Controller with an ADD action (get and post). When Add Spouse is selected in the Details view the AddSpouse Action is called which will create the new person (spouse) and then create the marriage. MY issue is that I need to pass the PersonID of the original person to the AddSpouse action in order to create a marriage. What is the best way to do that?
You can pass your personID in ViewData like this :
ViewData["PersonID"] = 1
and recover it in AddSpouse action
var id = ViewData["PersonID"]

Resources