开发者

Grails framework method addTo throws exception on multiple invoke

I want to add subscriptions to a User class, I do it by invoking the "addTo" method, here is my co开发者_JAVA技巧de:

if (params.jobs == "on") {
        user.addToSubscriptions(Category.findWhere(id: 1L))
    } else {
        user.removeFromSubscriptions(Category.findWhere(id: 1L))
    }

The "params" come from checkboxes, where the user can subscribe to a category by setting checkboxes. The code above is invoked when a form is submitted. What doesn't work is when the user changes more than 1 categories, think of the same code as above with different params.x, like this

    if (params.offers == "on") {
        Category cat = Category.get(2)
        if (!user.subscriptions.contains(cat))
        user.addToSubscriptions(Category.findWhere(id: 2L))//needs long variable
    } else {
        user.removeFromSubscriptions(Category.findWhere(id: 2L))
    }

What also happens only the category which is first in the code gets added and removed, all other throw the following exception:

org.hibernate.exception.GenericJDBCException: Could not execute JDBC batch update

edit:

the line in which the exception is thrown is this one though, which makes no sense to me

edit:

The exception gets thrown when I want to add a category, which is already added, it also doesn't get removed. (That's only for the categories which are not handled first in the code, don't ask me why)

     //reload page
    redirect(action: "userSettings")

What can I do?


Is it possible that you are trying to remove a category which is not associated with user? Like you know... user has no Category with id = 2 and he sent params.offers == "off" ?

Maybe you should do something like:

if (params.jobs == "on") {
    user.addToSubscriptions(Category.findWhere(id: 1L))
} else {
    Category cat = Category.get(2L)
    if (user.subscriptions.contains(cat)) {
        user.removeFromSubscriptions(cat)
    }
}

Few tips: If you have id, don't use:

Category.findWhere(id:1L) 

but:

Category.get(1L)

The error is thrown on the line you pasted, because it is probably last line of your controller, thus after this line yout transaction is committed where the error is thrown.

Try adding this code to your controller:

user.save()
user.errors?.allErrors?.each { println it }

this will print all errors which happened during save.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜