2012-01-13 85 views
3

Grails域类遇到问题。我重写构造函数从net.sf.json.JSONObject构建域类对象。当我通过控制器检测对象时,这工作正常。然后我尝试通过一个测试用例来实例化它,并且得到一个异常:Grails addTo *未创建

没有签名的方法:profileplugin.Contact.addToEmails()适用于参数类型:(java.lang.String)values:[something @ something.com]

我还应该指出,这似乎适用于某些类,但不适用于其他类。非常令人沮丧 - 我是新来的Grails,所以如果任何人都能指出我正确的方向,我会非常感激。

这是我的域类代码。

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); }; 
    }; 

} 

而且这里有一个例子源JSON字符串...

[ 
    addresses:[], 
    phones:["(555) 555-7011"], 
    faxes:[], 
    emails:["[email protected]"], 
    websites:["http://www.google.com"] 
] 

最后,这里是工作的代码的版本(以下获得反馈后):

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); }; 
    }; 

} 
+0

你能压缩的样本项目,所以我们可以看看? – Mengu 2012-01-13 01:35:44

回答

2

检查你的源代码,你不应该有一个,websites: String,的末尾我很惊讶它编译。

有没有理由把一个String类有很多关系(除非你想对它做数据库事务,那么最好是为电话,传真,电子邮件和网站创建域类)。你应该重写这个方法:

package profileplugin 

import net.sf.json.JSONObject 

class Contact 
{ 

    String[] phones=new String[] 
    String[] faxes=new String[] 
    String[] emails=new String[] 
    String[] websites=new String[] 

    ... 

} 

,然后使用:

this.emails.add(it) 

而且,可能更重要的是,你不应该将域名添加类中的业务逻辑,它应该是你的控制器内,服务或在某些外部类别(在src目录下)。

编辑: 其实并不正确编译,正确的语法是:

def emails = [] 
etc... 

得益于奔

+0

在java和groovy中,地图,数组或列表定义中的尾随逗号都很好 – 2012-01-13 13:07:08

+0

很有意思,谢谢! – fixitagain 2012-01-13 13:13:25

+1

“你*不应该*在你的域类中添加业务逻辑” - IMNSHO这是错误的部分。当然,Hibertate会干扰setter中的逻辑,但业务逻辑是域类的定义。 – 2012-01-13 15:26:46