Search code examples
ruby-on-railsrouteslink-to

ruby-on-rails - custom method and link_to


I have a program with users and projects (many to many relation). I would like to create my own methods: to delete all projects from specific user and to delete specific project from specific user, but I can't handle that. There is (quiet big) possibility I don't understand routes.

Below I insert code to delete all project from specific user.

In my user_controller.rb I have:

def delete_projects_from_user
    @user.projects.delete_all
end

In show.html.erb link_to:

<%= link_to 'Delete all projects', @user, method: :delete_projects_from_user, data: { confirm: 'Are you sure?' } %> 

And in routes I tried among others this two option:

resources :users do
    get 'delete_projects_from_user', on: :member
end

or

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

First option trows: "No route matches [POST] "/users/(id)" Second option just do nothing.

I will be grateful for prompt.


Solution

  • Basic format:

    <%= link_to 'DISPLAY TEXT', YOUR_ROUTE_path(@object), method:
     :HTTP_METHOD, data: { Additional html params } %>
    

    Here is the solution:

    <%= link_to 'Remove All Projects', delete_projects_from_user_path(@user), method: :post, data: { confirm: 'Are you sure?' } %>

    Then in your method:

     def delete_projects_from_user
       user = user.find(params[:id])
       user.projects.delete_all
       redirect_to :back #if nothing to render  
     end
    

    I'm sure this may help you.