我正在使用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时,无法保存该对象。我在运行应用程序之前更新了架构,因此它不应该是迁移问题。有什么想法吗?
答案 0 :(得分:0)
在这段代码中,您将email
,firstName
和lastName
分配给错误的对象:
// 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
。