Having trouble with Grails Domain Classes. I am overriding the constructor to build the domain class object from a net.sf.json.JSONObject. This works fine when I insantiate an object via a controller. Then I tried to instantiate it via a test case, and got an exception:
No signature of method: profileplugin.Contact.addToEmails() is applicable for argument types: (java.lang.String) values: [something@something.com]
I should also point out that this seems to work with some classes, but not others. Very frustrating — I’m new to Grails, so if anyone can point me in the right direction, I’d appreciate it very much.
Here’s my domain class code.
package profileplugin
import net.sf.json.JSONObject
class Contact
{
static hasMany =
[
phones: String,
faxes: String,
emails: String,
websites: String,
];
Contact() {}; // standard constructor must be specified, or grails dies
Contact(JSONObject source)
{
source.get('emails').each() { this.addToEmails(it); };
source.get('websites').each() { this.addToWebsites(it); };
source.get('phones').each() { this.addToPhones(it); };
source.get('faxes').each() { this.addToFaxes(it); };
};
}
And here’s an example source JSON string …
[
addresses:[],
phones:["(555) 555-7011"],
faxes:[],
emails:["someone@something.com"],
websites:["http://www.google.com"]
]
And, finally, here’s the version of the code that worked (after getting feedback below):
class Contact
{
def phones = [];
def faxes = [];
def emails = [];
def websites = [];
Contact() {}; // standard constructor must be specified, or grails dies
Contact(JSONObject source)
{
print source;
source.get('phones').each() { this.phones.add(it); };
source.get('emails').each() { this.emails.add(it); };
source.get('websites').each() { this.websites.add(it); };
source.get('faxes').each() { this.faxes.add(it); };
};
}
Check your source code, you should not have a
,at the end of yourwebsites: String,I am surprised it did compile.There is nosense to put hasMany relationship for a String class (unless you want to make database transaction on it then it is better to create domain classes for phones, faxes, emails and websites). You should rewrite this way:
and then use:
Also and probably more importantly, you SHOULD NOT add business logic inside your domain class, it should be inside your controller, service or in some external classes (under
srcdirectory).EDIT:
actually it does not compile properly, the right syntax is:
thanks to ben