简体   繁体   中英

Rails problems posting to users_controller action

I have an action in my users_controller that removes a user's picture.

  def use_fb_photo
    @user = User.find(params[:id])
    if @user.picture? and @user.uid
      @user.remove_picture!
      if @user.save
        redirect_to :back
      end
    end
  end

routes.rb

post 'users/:id/use_fb_photo', to: 'users#use_fb_photo', as: :use_fb_photo

I figured I would need to send the user id to this action using a form.

   <%= form_for @user, url: use_fb_photo_path, html: {id: "use-fb-photo-form", class: nil} do |f| %>
    <% end %> 

I want the user to trigger the action by clicking a button that is already inside a different form.

<button type="button" class="btn btn-default fb-photo" title="Use facebook photo"><i class="fa fa-facebook-square" aria-hidden="true"></i></button>

and the js

 $('.fb-photo').on('click', function () {
    $('#use-fb-photo-form').submit();
  });

I am getting the error No route matches [PATCH] "/users/17/use_fb_photo" .

If I change routes to patch ... instead of post I get a template missing error. I feel like I am making this too complicated but my brain is fried from coding all day.

I just want the user to click a button (that has to be inside another form) which removes the user's picture and redirects to their profile page.

form_for by default send PATCH , but your route waits POST . You can add method: 'post' to your form_for or change route to PATCH

I think you miss

method: :delete

in the call.

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