如何输入硬编码值到数据库?

时间:2014-07-05 17:56:20

标签: grails

我的User.groovy模型类中有几个字段

fName
lName
userName
pwd
yourTel

用户将进入上面显示的前4个字段。第5个字段yourTel将被硬编码。

def create() {
   [userInstance: new User(params)]
}

我该怎么做?

这是我已经尝试过的:

def create() {
    userInstance.yourTel = "2323232"
    params = userInstance.yourTe
    [userInstance: new User(params)] 
}

SAVE

def save() {
        def userInstance = new User(params)
        if (!userInstance.save(flush: true)) {
            render(view: "create", model: [userInstance: userInstance])

            return
        }else  {
            def userRole = Role.findOrSaveWhere(authority:'ROLE_USER')
            if(!userInstance.authorities.contains(userRole)){
                UserRole.create(userInstance, userRole, true)
            }
            redirect(controller:"login", action : "auth")
        }
    }

MODEL

static constraints = {
...
        yourTel blank:true , nullable: false

2 个答案:

答案 0 :(得分:1)

params是一张地图,因此请将您的数据设为

params.yourTel="2323232"

params.put("yourTel","2323232")

现在您的代码变为:

def create() {
    params.yourTel="2323232"
    [userInstance: new User(params)]
}

答案 1 :(得分:1)

您的方法也可以进行一些调整:

def create() {
    def instance = new User(params)
    instance.yourTel="2323232"
    [userInstance: instance]

}

左侧的[userInstance: instance]是您的模型将使用的键,右侧是您传递给它的键。在这里,您首先创建new User(params)然后将其与params绑定,然后您可以调整它并将其传递回您的模型。

def save() {
        def userInstance = new User(params)
        // set the yourTel to some value
        userInstance.yourTel="2323232" 

        if (!userInstance.save(flush: true)) {
            render(view: "create", model: [userInstance: userInstance])