Boolean value is not showing in Linux environment using Grails - grails

I am using Grails 2.4.0.And create an application and deploy on linux.
My Domain is
class UserDetails {
String userEnvironment = ""
Long userId = 0L
Boolean accountCreated = false
Integer retries = 0
String password = ""
boolean accountCreationInProgress = true
static constraints = {
accountCreationInProgress nullable : true
}
}
When saving its working fine on windows.But accountCreated and accountCreationInProgress column is blank on linux. Why don't know.
Anyone please help me out.

Change to:
class UserDetails {
StringuserEnvironment = ""
LonguserId= 0L
Boolean accountCreated= false
Integer retries = 0
Stringpassword= ""
Boolean accountCreationInProgress = true
static constraints = {
//there is no point to use nullable for accountCreationInProgress if you set it default to true value during create
}
}
Remember to drop table in database before rerun of app.

Related

Issues using findAllBy method to access a list of properties on an object

Here is the code to take a list of tags generated by params and passed into the service from the controller. I'm trying to filter the list of eateries to ONLY contain eateries with matching tag properties. I'm new to programming and grails so please forgive any silly mistakes:
class Eatery {
String name
String phone
Date lastVisited
List<Tag> tags
static hasOne = [location: Location]
static hasMany = [tags: Tag];
static constraints = {
name nullable: false, blank: false
phone nullable: true, blank: true
location nullable: true, blank: true
tags nullable: true, blank: true
lastVisited nullable: true, blank: true
}
public String toString() {
return name
}
}
Here is the service method:
Eatery getRandomEatery(List<Tag> tagList) {
List<Eatery> eateryList = Eatery.findAllByTags(tagList)
Random random = new Random()
Integer n = eateryList.size()
Integer selection = Math.abs(random.nextInt(n))
Eatery eatery = eateryList.get(selection)
return eatery
}
And here is the error:
Class
org.h2.jdbc.JdbcSQLException
Message
Parameter "#1" is not set; SQL statement: select this_.id as id2_0_, this_.version as version2_0_, this_.last_visited as last3_2_0_, this_.name as name2_0_, this_.phone as phone2_0_ from eatery this_ where this_.id=? [90012-164]
Around line 16 of grails-app/services/grubspot/RandomizerService.groovy
13://14:// }15: List<Eatery> eateryList = Eatery.findAllByTags(tagList)16: Random random = new Random()17: Integer n = eateryList.size()18: Integer selection = Math.abs(random.nextInt(n))19: Eatery eatery = eateryList.get(selection)
Change
List<Eatery> eateryList = Eatery.findAllByTags(tagList)
to
List<Eatery eateryList = Eatery.executeQuery("""
select e
from Eatery e left join e.tags as t
where t in (:tagList)""", [tagList: tagList])
I think you could make the query with a criteria with something similar to...
List<Eatery> eateryList = Eatery.withCriteria{
tags {
"in" "id", tagList.id
}
}
haven't tested it, but should give you an idea

How can i set default value in grails domain class

Is there any way to set a default value to domain class property?
I have a class called PayMethod, where I want the name property to default to "Cash" and I want this default value when I create this table, is this possible using Constraints?
package abc
import util.UserUtil
import embed.AuditUser
class PayMethod {
String name = "Cash"
AuditUser audit = new AuditUser()
static embedded = ['audit']
static constraints = {
name blank: false, size: 5..30, unique: true
}
static mapping = {
table 't01i0010'
id column: 'F_ID', precision: 4, scale: 0
name column: 'F_NAME', length: 30, defaultValue: 'Cash'
version column: 'F_REVISION'
}
def authUserService
int insertIndex = 0
int updateIndex = 0
static transients = ['authUserService', 'insertIndex', 'updateIndex']
def beforeInsert = {
audit.entryUser = UserUtil.user()
audit.entryDate = new Date();
}
def beforeUpdate = {
audit.reviseUser = UserUtil.user()
audit.reviseDate = new Date();
}
def afterInsert = {
if(insertIndex == 0){
def user = audit.entryUser
def date = audit.entryDate
log.info "POST INSERT => ENTERER: ${user} ENTERED: ${date}"
}
insertIndex++
}
def afterUpdate = {
if(updateIndex == 0){
def user = audit.reviseUser
def date = audit.reviseDate
log.info "POST UPDATE => REVISE: ${user} REVISED: ${date}"
}
updateIndex++
}
}
This will be possible in 2.2 which should be released this week or next. See http://jira.grails.org/browse/GRAILS-5520 for the relevant feature request. The syntax will be
static mapping = {
name defaultValue: "'Cash'"
}
For now you'll need to do what you're doing - set the value as the default value of the field. You can manually update the database schema, or do the work as part of a migration.
To build on the previous answer, you can use the defaultValue attribute in Grails 2.2 but you need to be careful to put double and single quotes around default values for String properties and double quotes around integer properties so that the default values appear correctly in the DDL. So, for instance, you need to use:
static mapping = {
myStringProperty defaultValue: "'Cash'"
myIntProperty defaultValue: "0"
}
If you only use single quotes, you will end up with an error like "Column "CASH" not found"
Also, as far as I can tell, default values do not work for properties that are enums.
Had the same issue and using static mapping didn't work for me either (using 2.2.3); the below link provided me a functional answer (set the default value in your object declarations):
http://grails.1312388.n4.nabble.com/How-to-set-a-default-value-for-column-td1383753.html
For String, encapsulate with quotes; int/integer should just be the value.
Hope this helps!

ASP.Net MVC : Get query values with no key

I have URL: http://site.com/page.aspx?update
how do I check if that update value is present?
HttpValueCollection treats that as an entity with null key. I have tried:
var noKeyValues = Request.QueryString.GetValues(null);
if (noKeyValues != null && noKeyValues.Any(v=>v==update)) ...
but it gives me a frowny line, because GetValues' argument is decorated with [NotNull].
so I end up doing:
var queryValuesWithNoKey =
Request.QueryString.AllKeys.Select((key, index) => new { key, value = Request.QueryString.GetValues(index) }).Where(
item => item.key == null).Select(item => item.value).SingleOrDefault();
if (queryValuesWithNoKey != null && queryValuesWithNoKey.Any(v => v.ToLower() == "update")) live = true;
not the most elegant workaround. Is there a better way to get key-less value from query string?
You can use
Request.QueryString[null]
to retrieve a comma separated list of keys with no values. For instance, if your url is:
http://mysite/?first&second
then the above will return
first,second
In your case, you could just do something like:
if(Request.QueryString[null] == "update")
{
// it's an update
}
if that's the only key you would use
Request.QueryString.ToString() to get the "update" value
I know I'm late to the party, but this a function that I use for this kind of task.
internal static bool HasQueryStringKey(HttpRequestBase request, string key)
{
// If there isn't a value, ASP will not recognize variable / key names.
string[] qsParts = request.QueryString.ToString().Split('&');
int qsLen = qsParts.Length;
for (int i = 0; i < qsLen; i++)
{
string[] bits = qsParts[i].Split('=');
if (bits[0].Equals(key, StringComparison.OrdinalIgnoreCase))
{
return true;
}
}
return false;
}
You may need to update it so that it is case sensitive, or uses different arguments depending on your purposes, but this has always worked well for me.

Null or false value in grails

I have a domain class in which one of its fields is of type Boolean. When I retrieve it, how can I differentiate whether it's set to false or it's null ?
Thanks
if(field == null) will work as expected.
Here's a simple example that demonstrates how to test for all 3 possible values of a Boolean
class Person {
Boolean isMale = false
Boolean isFemale = true
Boolean isAdult = null
}
def p = new Person()
assert !p.isMale
assert p.isFemale
assert p.isAdult == null
You can run this code in the Groovy console to verify the expected behaviour

Making Grails data-binding interpret empty String values ("") as zero (0)

This question is about altering how the Grails data-binding handles string-to-integer conversion.
Consider the following domain object:
class Foo {
String name
Integer price
}
Furthermore, assume that the domain object is populated from HTTP request parameters:
def foo = new Foo(params).save()
The save() method above will fail if params.price == "" (empty string). I'd like to change this behaviour globally so that an empty string is parsed as zero (0) when converting from a string to an integer in Grails data-binding. How do I achieve that?
added a filter see the setion 5.5.1 Events and Auto Timestamping in the grails documentation (http://grails.org/doc/1.1.x/index.html)
def beforeInsert = {
if (price == '') { price = 0}
}
Instead of changing the data binding why not just write your own setter? In the setter test to see if the string is empty, if it is set price to 0. If it isn't do a normal integer conversion.
try this constraint instead
static constraints = {
price(validator: {val, obj ->
if (val == '' || val == 0) {
obj.price = 0
return true
} else if (val < 1) {
return false;
}
})
}
import org.grails.databinding.BindUsing
class Foo {
String name
#BindUsing({ obj, source ->
source["price"] ?: 0
})
Integer price
}

Resources