Daniel T.
Daniel T.

Reputation: 38430

In Grails, how do I tell if an object is transient or not?

I have a piece of code in Grails:

def product = Product.get(5) ?: new Product()
product.isDiscounted = product.isDiscounted ?: true

Problem is, if the isDiscounted property is already set for an existing product and it's false, I'll end up changing it to true. Is it possible to check if an object is transient?

Upvotes: 3

Views: 1038

Answers (1)

Burt Beckwith
Burt Beckwith

Reputation: 75681

In this case make the property Boolean instead of boolean, then the initial value will be null and not default to false. This will help validation too, since you can verify that a choice of false was intentional, and not just allowing the default value.

In general though you can use the isAttached() method (or the property style variant attached), e.g.

def product = Product.get(5) ?: new Product()
product.isDiscounted = product.attached ? product.isDiscounted ? true

This case can actually be even more compactly done with a default value in the constructor:

def product = Product.get(5) ?: new Product(discounted: true)

Upvotes: 5

Related Questions