1

I'm trying to have my custom update action for my user controller render the edit page if they fail to validate, like so:

def update
  user = User.find(params[:id])
  user.update(user_params)
  # zero because checkbox
  user_params[:banned] == "0" ? user.remove_role(:banned) : user.add_role(:banned)
  if user.banned_note
    if user.banned_note.update(content: params[:user][:reason_for_ban])
      redirect_to "/admin/users/#{params[:id]}"
    else
      render "edit.html.erb"                                    # this line
    end
  end
end

def find_resource(param)
  User.find!(id: param)
end

I want to render the edit page with a flash message listing the errors, but what I have doesn't work. I'm not sure how to route to the correct action, since there's no actual view or edit action (which are auto generated by the Administrate gem).

PandyZhao
  • 137
  • 1
  • 11

1 Answers1

3

Pandy, I have not used this gem but looking the source code and this comment of this issue in GitHub, Have you try the following?

def update
  user = User.find(params[:id])
  user.update(user_params)
  # zero because checkbox
  user_params[:banned] == "0" ? user.remove_role(:banned) : user.add_role(:banned)
  if user.banned_note
    if user.banned_note.update(content: params[:user][:reason_for_ban])
      redirect_to "/admin/users/#{params[:id]}"
    else
      #This two lines
      flash.now[:notice] = "Something"
      render :new, locals: {
        page: Administrate::Page::Form.new(dashboard, resource),
      }
    end
  end
end

def find_resource(param)
  User.find!(id: param)
end
MatayoshiMariano
  • 2,026
  • 19
  • 23
  • Thanks for the response Matayoshi. I did try something similar to that, but I get `undefined method or variable: resource` when that happens. I think that's on the right track but I'm not sure how to manipulate it so I could use it. – PandyZhao Aug 04 '17 at 21:18
  • 1
    Try `user` instead of `resource` – MatayoshiMariano Aug 04 '17 at 21:26
  • Works!!! Thanks so much! How did you get to that answer? I was looking at that action in their docs: http://www.rubydoc.info/github/thoughtbot/administrate/Administrate/ApplicationController#edit-instance_method But I didn't know to replace `requested_resource` with `user`. – PandyZhao Aug 04 '17 at 21:29
  • Sorry if it's a loaded or stupid question. I just want to know your thinking process. Thanks again for the help! – PandyZhao Aug 04 '17 at 21:37
  • 1
    @PandyZhao it OK, it is a good question! You were close, the only thing is that you do not defined the `resource` variable, you defined as `user`. The resource is in this case is the User, because it is the UsersController – MatayoshiMariano Aug 05 '17 at 17:32