2013-02-11 63 views
0

如何在grails中保存类的扩展? 例如我有类用户和管理员Grails保存扩展类

class User { 
    String name 
    String password 
} 

class Administrator extends User { 
    String authoritySelected 
} 

例如类用户,我有保存“USER1”, ,然后我想改变类用户user1级管理员和更新authoritySelected

def update(){ 
    def user1 = User.get("user1") 
    user1.authoritySelected 
    user1.save(flush:true) 
} 

并得到错误:

没有这样的属性:authoritySelected类:用户

那么,如何保存在类中选择User并将其更改为类Administrator?谢谢。

回答

0

当你说“然后我想更改user1从班级用户到班级管理员”,你究竟想要做什么?

您正试图访问该对象中不存在的对象的属性。向下转换根本不能像那样工作。您应该实例化一个类型为Administrator的对象,以便在其后保存其属性之一。

1

说到语法,你写的代码没有意义。谈论设计,也没有。

我可以建议你在尝试做这种事情之前学习一点OOP吗? :)

但让我们面对你提交的问题。

第一个建议:不要为你的应用程序实现安全系统,有很多东西可以为你做。首先是:Spring Security plugin

第二:你写的代码不起作用,因为扩展一个类是使父类的另一个类“子”的方法。在你的例子中,管理员是用户的儿子。

def update(){ 
    def user1 = User.get("user1") // I don't get how this should work, but I'll leave it like this in this example 
    user1.authoritySelected // you're trying to GET the value a property that doesn't exist in the User class, you should SET something here 
    user1.save(flush:true) 
} 

如果你希望你的用户更改角色,最简单的认为想在角色并不像其它类,而不是它应该是用户的属性,所以你可以改变它。一旦创建了一个类的实例,就不能改变它(可能这不完全正确,但不应该)。

OK,一些代码:

class User { 
    String name 
    String password 
    String authority // a property of the class you can change 
} 

def update(){ 
    def user1 = User.get("user1") 
    user1.authority = 'Administrator' // change the property on the instance you retrieved 
    user1.save() // save the instance itself 
} 

这仍然不是一个好的设计方案给我,我只是试图让你能够看到你在做什么错。

0

,如果你想创建你需要创建一个用户的实例的用户,例如:

User u = new User(name: "xpto", password: "xptopass").save(flush:true) 

管理员是用户太多,但有一个数据越多,authoritySelected,所以如果管理员延伸用户,他也拥有和用户一样的数据。

Administrator a = new Administrator(name: "xpto", password: "xptopPass", authoritySelected: "ADMIN").save(flush:true) 

注意,Object.get(X)的方法需要一个ID(长), “X” 是一个长值,而不是字符串。 http://grails.org/doc/2.3.x/ref/Domain%20Classes/get.html