I have built a ruby on rails app that lets users track their workouts. User has_many workouts. In addition, a User can create a box (gym) if they are a gym owner. Users can then associate with that box through a Membership resource.
I create that association for the current_user with a remote form in /views/boxes/show.html.erb:
<% remote_form_for Membership.new do |f| %>
<%= f.hidden_field :box_id, :value => @box.id %>
<%= f.hidden_field :user_id, :value => current_user.id %>
<%= submit_tag "I am a member of this box" , :class => '' %>
<% end %>
I now want to give the current_user the ability to remove their association. How do I structure the link/form and what should the memberships_controller destroy action look like?
Below is a list of my associations if it helps:
User
class User < ActiveRecord::Base
has_many :boxes
has_many :workouts, :dependent => :destroy
end
Workout
class Workout < ActiveRecord::Base
belongs_to :user
belongs_to :box
end
Box
class Box < ActiveRecord::Base
belongs_to :user
has_many :users, :through => :memberships
has_many :workouts, :through => :users
has_many :memberships
end
Membership
class Membership < ActiveRecord::Base
belongs_to :user
belongs_to :box
end
After you have done the changes suggested here, and assuming that you have obtained the membership for the current_user and the box using the following code,
create a link for the user to delete the membership as follows.
Membership controller should have a destroy method that looks like the following.
This is assuming that your memberships controller is restful and you have
map.resources :membershipsin your routes.