Grails中两个域类的值的唯一约束 [英] Unique Constraint over values of two domain classes in Grails

查看:341
本文介绍了Grails中两个域类的值的唯一约束的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个域类。一个是:

I have two domain classes. One is :

 class User {
    String login
    String password
    String firstName
    String lastName
    String address
    String email

    static constraints = {
        login blank:false, size:5..15,matches:/[\S]+/, unique:true
        password blank:false, size:5..15,matches:/[\S]+/
        firstName blank:false
        lastName blank:false
        email email: true
    }
 }

class AddWebsite {

String website
User user
static constraints = { 
                     website blank:false 
                     website(unique: ['user'])
                     }
}

我在后端使用MongoDB。我需要一个特定的登录值,所有siteURL值应该是唯一的。例如:login = abc@gmail.com。然后,该用户可以仅在数据库中具有所有唯一的网址。但是相同的网址可以存在为不同的用户。我如何使用唯一约束或任何其他方法?

I am working with MongoDB at the backend. I need that for a particular login value, all siteURL values should be unique. Ex: login = abc@gmail.com. Then this user can have all unique url only in the database. But same urls can exist for different users. How do I do that using the unique constraint or any other approach?

推荐答案

它终于工作。我得到的用户不能为空错误,而进入网站虽然它没有在AddWebsite域类中验证。我进行了以下更改并使其工作:

It finally worked. I was getting the user cannot be null error while entering the website though it was not being validated in the AddWebsite domain class. I made the following changes and got it to work:

class AddWebsite{
    String website
    User user
    static belongsTo = [user: User]
    static constraints = {
        website( url:true, unique: ['user'])
    }
}

在我的控制器中,我将用户对象的值设置为会话变量:

And in my controller also, I set the value of the user object to the session variable:

def addWebsites() {
    if(request.method == 'POST') {
        def w = new AddWebsite()
        w.properties[
                    'website'
                ] = params
        w.user = session["user"]                       //modified to make it work
     if(w.save()) {
            render view:'addWebsites', model:[message: "Successfully saved"]
        }
        else {
            return [addWebsite:w]
        }
    }

希望它帮助别人:)

这篇关于Grails中两个域类的值的唯一约束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆