Deleting an associated record through a remote_form
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
class Workout < ActiveRecord::Base belongs_to :user belongs_to :box end
class Box < ActiveRecord::Base belongs_to :user has_many :users, :through => :memberships has_many :workouts, :through => :users has_many :memberships end
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,
@membership = current_user.memberships.for_box(box).first
create a link for the user to delete the membership as follows.
link_to 'Delete Membership', membership_path(@membership), :method => :delete
Membership controller should have a destroy method that looks like the following.
def destroy @membership = Membership.find(params[:id]) @membership.destroy end
This is assuming that your memberships controller is restful and you have map.resources :memberships in your routes.