I've got devise working for my User class, and I'm trying to add some CRUD methods to the users controller. I've read about routing for this, and so long as devise_for
comes before resources
it will take precedences, otherwise you will only be accessing non-existent records via /users/sign_in or whatever. Anyway.
I have my CRUD methods working, and even some resources. Sa开发者_StackOverflow社区y users have many possesssions. I can view a possessions via /users/1/possessions/1, but when I try to delete it, I don't have access to the Devise current_user method. I could delete by looking up the User with params[:user_id], and then finding it's possessions by params[:id], but that's not really secure if I only want the logged in user to be able to delete his/her own possessions.
How can I use Devise's methods from within my User model's CRUD methods?
Using "current_user" in models in Ruby on Rails
http://rails-bestpractices.com/posts/47-fetch-current-user-in-models
A better practise might be to not nest the possessions route under user, instead have it on its own as /possessions/1
and the in your possessions controller to scope all of your finds by the current_user i.e.:
def index
@possessions = current_user.possessions
end
def edit
@possession = current_user.possessions.find(params[:id])
...
end
That way you can be sure that the user will only ever be able to see their own items, and they will receive a 404 if they tried to access someone else's possessions.
Inherited Resources makes this really easy to do, so you can code your controllers like this:
class ProjectsController < InheritedResources::Base
protected
def collection
@projects ||= end_of_association_chain.paginate(:page => params[:page])
end
end
精彩评论