简体   繁体   中英

Using Devise in Rails4, how to allow users to only the edit their own comments?

I'm confused with how to use Devise's current_user helper in my views and controllers. Do I need to do a migration to add user_id in my database tables? Do I need to do something with the sessions controller?

Here is my routes file:

 devise_for :users

  resources :groups, shallow: true do
      resources :ideas do
           resources :comments
      end
  end 

Sign in / sign up etc. is working fine. I would like to allow users to edit only the ideas and comments, that they created.

Do I need to add in my applications controller a helper method, for example:

  def current_user
    @current_user ||= User.find(session[:user_id]) if session[:user_id]
  end

  helper_method :current_user

Then, in theory, I should be able to do the following?

   <% if current_user %>
       <%= link_to 'Edit', edit_idea_path(@idea) %>
   <% end %>

And then I also need to I guess update my controller edit action with current_user? Eg ?

    @comment = current_user.comment.find(params[:id])

i think what you are trying to do is:

  <% if current_user.id == @idea.user.id %>
       <%= link_to 'Edit', edit_idea_path(@idea) %>
  <% end %>
<% if current_user.id == @idea.user.id %>
   <%= link_to 'Edit', edit_idea_path(@idea) %>
<% end %>

Would kinda work, but it is about as secure as an unlocked door. It doesn't explicitly prevent a user from going to /idea/5/edit and making those changes (even if they didn't create/own idea 5). As mentioned above: either use CanCan or roll your own solution in the controller on the :update method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM