How can I filter a list in Grails based to only display what 'belongsTo' a particular user?
I'd imagine the answer is pretty basic, but I'm quite new to Grails and struggling to find the answe开发者_开发问答r to my question anywhere else.
Basically, I have two domain classes, Users and Events. The events has a 'belongsTo' relationship with the User and the User has a 'hasMany' relationship with the Events. The application requires a user to log in. Once logged in they can view a list of created events, however the list contains all of the created events; even those created by other users. How can I filter the list to only show what the logged in user has created? I don't want one user to be able to access and alter events created by another.
Ethan's answer is correct, and easy to do. But if you have a lot of different places you need then filtering, then you're a bit a risk of forgetting to do the filter.
You can use the hibernate filter plugin to automatically filter all the data. See http://trac.serveall.net/web/ibidem for an example where I filter data based on the current user's company.
If your controller has the logged in user's id, you should be able to do
user = User.get(id)
def events = user.events
and pass that on to your view:
redirect(controller: 'event', action: 'list', userEvents:events)
精彩评论