【问题标题】:Can't save data in database in Grails manually but with dbconsole it works well无法手动将数据保存在 Grails 中的数据库中,但使用 dbconsole 可以正常工作
【发布时间】:2017-09-11 15:52:04
【问题描述】:

Register.gsp 页面,当我提交表单时,它呈现良好并转到列表页面。但问题是它不保存任何数据。如果我通过dbconsole添加数据,那么list.gsp会显示数据。可能是个愚蠢的问题,但我是 Grails 的初学者。提前致谢。

域类:

 package userreg

 class Customer {

 String name
 Date birthday
 String gender
 String email


static constraints = {
    name blank: false
    email blank: false,unique:true
  }
}

控制器:

package userreg

class CustomerController {
static allowedMethods = [save: "POST", update: "PUT", delete: "DELETE"]

def index ={
     render(view:'register')

}

def register()
{

}

def save ={
  def customer=new Customer(params)
  customer.save flush:true
  redirect action:"list"
  }


def list() 
{
 def customers=Customer.list()
 [customers:customers]
}
}

查看 - 注册:

register.gsp
<!doctype html>
  <head>
 <title>Registration </title>
</head>
<body>
<div class="body">
<g:form controller="customer" action="save" >
 <table>
 <tr><td>Name</td><td><g:textField name="name"/> </td></tr>
 <tr><td>Birthday</td><td><g:datePicker name="date" value="${new Date()}"
          noSelection="['':'-Choose-']"/></td></tr>
 <tr><td>Gender</td><td><g:radio name="gender" value="female"/>Female
        <g:radio name="gender" value="male"/>Male</td></tr>
 <tr><td>Email</td><td><g:textField name="email" value="user@email.com"/>
  </td></tr>               
  <tr><td></td><td><g:submitButton name="save" value="save" /> </td></tr>
  </table>

  </g:form>
  <div>
 </body>
</html>

列表 - list.gsp:

<!doctype html>

<head>
    <title>List of Customers </title>
</head>

<body>
    <table border=1>
        <tr>
            <th>Name</th>
            <th>Gender</th>
            <th> Birthday</th>
        </tr>
        <g:each in="${customers}" var="customer">
            <tr>
                <td>${customer.name}</td>
                <td>${customer.gender}</td>
                <td>${customer.birthday}</td>
            </tr>
        </g:each>
    </table>
</body>

</html>

【问题讨论】:

  • 您的问题是什么?你想做什么,你尝试了什么,你得到了什么结果?更新问题的正文。提醒:这里没有人愿意为您调试代码。你需要表明你愿意做这项工作。

标签: database grails gsp


【解决方案1】:

您的模型没有保存可能是因为它有验证错误。

改变

def save ={
  def customer=new Customer(params)
  customer.save flush:true
  redirect action:"list"
}

到这里

def save ={
  def customer=new Customer(params)
  customer.save flush:true, failOnError:true
  redirect action:"list"
}

它会抛出一个错误,解释它无法保存模型的原因。

【讨论】:

  • 更好的办法是检查调用.save(...) 的返回值或检查errors 属性。
猜你喜欢
  • 1970-01-01
  • 2015-02-24
  • 2017-11-24
  • 1970-01-01
  • 2019-02-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多