【问题标题】:The object of UserProifle cannot be saved for ShiroUser无法为 ShiroUser 保存 UserProifle 的对象
【发布时间】:2012-02-21 17:34:31
【问题描述】:

我正在开发一个 Grails 应用程序,我正在尝试将 ShiroUser 与 UserProfile 联系起来。 我有两个模型,称为 ShiroUser 和 UserProfile。在我的 ShiroUser 中:

class ShiroUser {
    ... ...
    static hasOne = [profile: UserProfile]
    static constraints = {
       email(nullable: false, blank: false, unique: true)
       profile(nullable: false)
    }
}

在我的 UserProfile.groovy 中,我有:

class UserProfile {
    ... ...
    static belongsTo = [shiroUser:ShiroUser]

}

但是,在我的 ShiroUserController.groovy 中,当我尝试创建一个新的 ShiroUser 实例时,它的效果并不好。这是我的代码:

 def create() {
        [shiroUserInstance: new ShiroUser(params), userProfileInstance: new  UserProfile()]
    }
def save() {

        //todo add validation for email and password here.
        def shiroUserInstance = new ShiroUser(params)

        // Create a user profile
        def userProfileInstance = new UserProfile()
        shiroUserInstance.profile.email = params.email
        shiroUserInstance.profile.firstName = params.firstName
        shiroUserInstance.profile.lastName = params.lastName

        if (!userProfileInstance.save(flush: true)){
            render(view: "create", model: [userProfileInstance: userProfileInstance])
            return
        }
        shiroUserInstance.profile = userProfileInstance

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

        flash.message = message(code: 'default.created.message', args: [message(code: 'shiroUser.label', default: 'ShiroUser'), shiroUserInstance.id])
        redirect(action: "show", id: shiroUserInstance.id)
    }

当我转到我的应用程序并尝试创建新的 ShiroUser 时,无法保存该对象。我在运行应用程序之前更新了架构,因此它不应该是迁移问题。有什么想法吗?

【问题讨论】:

    标签: grails groovy


    【解决方案1】:

    在这段代码中,您似乎将emailfirstNamelastName 分配给了错误的对象:

        // Create a user profile
        def userProfileInstance = new UserProfile()
        shiroUserInstance.profile.email = params.email
        shiroUserInstance.profile.firstName = params.firstName
        shiroUserInstance.profile.lastName = params.lastName
    

    试试这个:

        // Create a user profile
        def userProfileInstance = new UserProfile()
        userProfileInstance.email = params.email
        userProfileInstance.firstName = params.firstName
        userProfileInstance.lastName = params.lastName
        shiroUserInstance.profile = userProfileInstance
    

    然后,您应该可以只保存shiroUserInstance,如果您正确设置了映射,它也应该自动保存userProfileInstance

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-03
      • 2016-11-15
      • 2016-11-20
      • 2018-04-26
      • 2021-01-28
      • 1970-01-01
      相关资源
      最近更新 更多