I have a domain class
class Something {
String name
String email
List<String> friends = []
}
In the domain class itself I have a method for Something objects which populates the friends list. But for some reason I am not able to persist this list. and it gets made null on browsing away from the gsp relevant to the domain modifying action.
Any suggestions as to why this is happening?
I think you instead need to write your domain as:
class Something {
String name
String email
List friends
static hasMany = [ friends: String ]
}
Related
Suppose I have two domains:
class Country {
String name
String Desc
static hasMany = [organizations: Organization]
}
class Organization {
String name
Country country
static belongsTo = [country:Country]
}
Note: In case of create Organization, countries will be listed in a combobox.
Suppose I have 4 row in my database which I have fetched from bootstrap.
**Name** **Desc**
US USA
CA CAN
NP NEP
IN IND
I want to assign USA as a default value while create a Organization. Is there a way to do it from domain level not gsp?
I think the load method is your best bet, although it requires that you know the id of the instance that you want to be the default. It's not a good idea to hard-code this because it could change in the future. But you can look it up when the app starts and save the id, e.g.
class BootStrap {
def grailsApplication
def init = {
def usa = Country.findByName('US')
grailsApplication.config.COUNTRY_US_ID = usa.id
}
}
Use whatever Config key you want of course.
Then change the Organization class to call load in its constructor:
import grails.util.Holders
class Organization {
Organization() {
if (Holders.config.COUNTRY_US_ID) {
country = Country.load(Holders.config.COUNTRY_US_ID)
}
}
String name
static belongsTo = [country:Country]
}
Note that I removed the Country country property because it's redundant; adding that belongsTo creates a property with the same name as the map key ("country") and with the same type as the map value (Country). It doesn't hurt to have it, but it's not needed.
The reason load is appropriate here is that it doesn't hit the database until you access a persistent property other than id. So you're configuring it to lazily retrieve the real instance if necessary, but if you overwrite the value with a different instance, you won't have wasted a database lookup for the initial population. Turn on SQL logging to verify this.
I want to create a domain class as like , One user can post many orders [Bidirectional] and one order can be liked by many users [unidirectional].
I have written a domain class as shown below ,
Class User {
String userName;
List orders
static hasMany = [Order]
}
Class Order {
String orderId
String orderName
//Indicates this order belongs to only one user
static belongsTo =[owner : User ] // Bidirectional
//Indicates order can be liked by many users
static hasMany = [likedUser : User] //Unidirectional
}
But I am getting am error saying invalid schema . Any body please help...
This post looks similar to my question but I am not getting , Please help.
First, order is a reserved word in SQL. Since GORM by default creates a table with the same name as your class, you'll need to either rename your class or provide a different name to use when mapping to SQL tables.
For example:
class Order {
static mapping = {
table 'user_order'
}
// ...
}
Another problem is that Order contains two associations to User. You need to tell GORM which one of these that is the bi-directional association from User to Order. That can be achieved using mappedBy, like this:
class User {
String userName
static hasMany = [orders: Order]
static mappedBy = [orders: 'owner']
}
Hope this helps.
please help me
I have this class
Class Person
{
String name
String id
Date date
}
This class is connected with mysql
my question is where put this:
Person.count() or
Person.findByAllName("Carlos")
Class Person
{
String name
String id
Date date
def person = Person.count() //here???
}
I want to create a field person that show how many register have the table.
is possible with scaffold only, because have error the moment of run app?
Thanks and sorry by my bad english¡¡¡
The correct place would be outside the domain class. Also, you need not define the Id on the domain class, as it is autogenerated
This a continuation of this question.
I have an Address class which contains basic street address information. I also have a User class which has the attributes physicalAddress, mailingAddress, cargoDestinations, and cargoSources. The User class looks something like this:
class User {
String username
String password
String firstName
String lastName
String businessName
String phoneNumber
Address physicalAddress
Address mailingAddress
static hasMany = [accounts:Account, cargoSources:Address, cargoDestinations:Address, cargoes:Cargo, loadsLogged:Load, loadsDelivered:Load]
Set accounts, cargoSources, cargoDestinations, cargoes
static mappedBy = [loadsLogged:"loggedBy", loadsDelivered:"deliveredBy"]
//some other stuff after this
And the Address class looks something like this:
class Address {
static belongsTo = [user:User]
String streetAddress
String city
String state
String zip
BigDecimal taxRate
//some other stuff after this
I followed the tutorial here for the most part. In step 5 my template looks like this:
<g:select
from="${account.user.cargoDestinations}"
name="cargoDestinations" value="">
</g:select>
The problem is that instead of returning only cargoDestinations, the template returns ALL addresses associated with that user. If I change from="${account.user.cargoDestinations}" to from="${account.user.physicalAddress}" or from="${account.user.mailingAddress}" I get the expected result, so I know my problem has something to do with how the cargoDestinations variable is mapped. How can I go about fixing this without changing my class files too much?
The way you have your addresses mapped, they all link back to the user on the user_id column. You'll need to add some fields to Address to distinguish how they're related to User, similar to how you've mapped Loads. For example:
class Address {
static belongsTo = [cargoSourceFor: User, cargoDestinationFor: User]
...
}
class User {
...
static hasMany = [cargoSources:Address, cargoDestinations:Address]
static mappedBy = [cargoSources: "cargoSourceFor", cargoDestinations: "cargoDestinationFor"]
...
}
If you're familiar with SQL, doing a grails schema-export and looking at target/ddl.sql can be helpful when setting up mappings.
I ended up adding several boolean fields to my address class, which made the design simpler and much easier to work with. This way I only need one class instead of several nearly identical classes. The boolean fields in the Address class now indicate if an address is a physical address, mailing address, cargo source, etc., or all of the above. As #ataylor pointed out, this system makes it so an address object can only be associated with one user from my User class, but it does not seem like that will ever be an issue. The worst case is that a multiple users would have the same address in real life, and my program would require the creation of a separate address object for each of those users, even though the addresses in question would be identical.
Is it possible in grails to sort query results according to a property of a parent class in a relationship. E.g. I have a user domain class which has a one to many relationship with a list of Tasks.
When showing the list page of the Tasks domain class, I want to be able to sort the list of tasks by the associated User name.
class User {
String name
String login
String group
List tasks = new ArrayList()
static hasMany = [tasks:Task]
}
class Task {
String summary
String details
User user
static belongsTo = [user:User]
}
I can do something like this
Task.list([sort:"user", order:"asc"])
But this sorts by the user.id, is there a way to specify the sort to be on the user.name?
You can do it using Criteria
def criteria = Task.createCriteria()
def taskList = criteria.list {
createAlias("user","_user")
order( "_user.name")
}
iirc, grails sorts by using toString() and since you have not supplied one, it uses the id.