0

I've a simple problem but have been struggling with it for many hours. I've these two models in my rails app:

class User < ActiveRecord::Base
  has_and_belongs_to_many :groups
 end

and

class Group < ActiveRecord::Base
  has_and_belongs_to_many :users
end

and this controller:

class GroupsController < ApplicationController
def show
  @group = Group.find(params[:id])
  @users = @group.users
end

and I need to display a view which shows one particular group with its relative users and next to each user is a link for removing the user from the association upon hitting the remove button. My current version of views/groups/show looks like this:

<p>Description: <%= @group.description if @group.description %></p>
  <p>Associated Users:
   <ul> 
    <% @users.each do |user| %>
     <li>
       <%= link_to user.email %>
       <%= link_to user.name %>
      <button>
       <%= link_to("Remove user from group", @group.users.delete(user),
       :data => { :confirm => "Are you sure?" }) unless user == current_user %>
      </button>
     </li>
    <% end%>  
   </ul>
  </p>

Which "works" but when I then refresh the page delete method is executed and the association is deleted without hitting the button. I tried using the partial and many other different ways but couldn't figure it out. Can you please help?

bosp
  • 107
  • 10

1 Answers1

1

In just rendering the page, you are executing @group.users.delete(user) so of course they're being deleted when the page is displayed. It's not happening on refresh... on refresh you're just seeing the results of your last render.

You need to define a route in your routes.rb that will call an action when you follow the link_to, then the link_to should direct to that route path.

Maybe something like this in your routes...

resources :groups do
  member do 
    get 'detach'
  end
end

Then your link to looks like...

   <%= link_to("Remove user from group", detach_group_path(@group, user_id: user.id),
   :data => { :confirm => "Are you sure?" }) unless user == current_user %>

And finally you have an action in your groups controller to do the detaching...

def detach
  group = Group.find(params[:id])
  user = User.find(params[:user_id])
  group.users.delete(user)
  redirect_to group_path(group)
end
SteveTurczyn
  • 36,057
  • 6
  • 41
  • 53
  • Great, thank you for your advice. I was pondering upon such solution but as a beginner couldn't sew it together. For future reference - just a small typo there in controller should be redirect_to. – bosp Dec 18 '15 at 14:27