How to do browser-based new user approval by Admin

2019-07-23 18:46发布

问题:

I created a simple directory using Rails 3.2 and devise where new users need approval before they can use the site. I followed the instructions in "How To: Require admin to activate account before sign_in" and admin users can now see lists of different index pages of approved versus non-approved users. So far so good.

My problem is the user approval process. Currently I approve users in the Rails console. I'd like for admin users to be able to approve users through their browser. I'm at a loss. I know I need to put "approve" and "don't approve" links next to each unapproved user but then what?

In the abstract I know that clicking those links should activate a method in the User model or controller and then redirect with flash but I've strayed beyond what I know from my beginner tutorials.

I'm not sure what to put in my views and routes. Do I need a special hidden form that only changes 'approved' from false to true when when the "approve" submit button is clicked and the button is the only visible element?

If anyone can get me started in the right direction I can probably figure it out from there.

回答1:

@sas1ni69's comment lead me to Ruby on Rails link_to With put Method which allowed me to find a solution.

To my view I added:

<%= link_to "approve", approve_user_path(user.id)  %>

To my routes I added:

match 'users/:id/approve'=> 'users#approve_user', as: 'approve_user'

To my user controller I added:

def approve_user
  user = User.find(params[:id])
  user.approved = true
  if user.save
    flash[:notice] = "#{user.full_name} approved"
  else
    flash[:alert] = "#{user.full_name} approval failure"
  end
  redirect_to :back
end

Seems to be working like a charm! Thanks everybody!