Reputation: 11011
The code below is working but I want to know if there is a better way to do it. Is this the correct RESTful way to do this? Any suggestions would be helpful. The basic requirement is that I need a way to create and destroy a membership from places/show.html.erb
class Place < ActiveRecord::Base
has_many :memberships
has_many :members, :through => :memberships, :source => :user
def membership_for_user(user)
self.memberships.select{|m| m.user_id == user.id}
end
end
class User < ActiveRecord::Base
has_many :memberships
end
class Membership < ActiveRecord::Base
belongs_to :user
belongs_to :place
end
class MembershipsController < ApplicationController
def create
@membership = Membership.new({:user_id => current_user.id, :place_id => params[:place_id]})
unless @membership.save
flash[:notice] = "Unable to become member."
end
redirect_to place_path(params[:place_id])
end
def destroy
@membership = Membership.find(params[:id])
place_id = @membership.place_id
@membership.destroy
redirect_to place_path(place_id)
end
end
places/show.html.erb
<%= link_to 'Join', memberships_path(:place_id => @place.id), :method => :post %>
<%= link_to 'Cancel', @place.membership_for_user(current_user), :method => :delete %>
Upvotes: 0
Views: 585
Reputation: 2926
@klochner is right; this is wrong. You need to create the membership beforehand and have a status attribute on the Membership, which you either update to "accepted" or just delete the membership, if you want to do it this way. Otherwise you need a form to create the membership first.
Upvotes: 0
Reputation: 8125
This looks odd - how can you both create and delete a membership on the same page?
Are you selecting one or the other of the link_to statements, or can a user have multiple memberships to the same place?
I'd consider:
Upvotes: 1