2012-07-09 7 views
4

이벤트 모델이 있고 사용자 모델이 참석자 모델을 통해 참가했습니다. 인증 된 사용자로 "참석"하는 방법을 알아 냈습니다. 그러나 내가 알 수없는 것은 사건에서 "철회"하는 좋은 방법입니다. 이게 내가 누락 된 것이 사소한 것이지만, StackOverflow에 들어가기위한 더 좋은 방법은 사소한 것을 묻는 것보다 낫다고 확신한다. 오 나는 몇 시간 동안 railscasts과 SO 검색을 해왔다. ...레일 has_many : 연결을 통해. 링크와의 연결을 제거 하시겠습니까?

고마워!

보기/이벤트/show.html.erb

<p><strong>Attendees: </strong> 
    <ul> 
     <% for attendee in @event.users %> 
      <% if attendee.username == current_user.username %> 
       <li><strong><%= attendee.username %></strong> 
        <%= link_to 'Withdraw From Event', withdraw_event_path(@event.id), :method => :post, :class => 'btn btn-danger' %> 
        <%= link_to 'Destroy', @attendee, confirm: 'Are you sure?', method: :delete, :class => 'btn btn-danger' %> 
       </li> 
      <% else %> 
       <li><%= attendee.username %></li> 
      <% end %> 
     <% end %> 
    </ul> 
</p> 

/controllers/events_controller.rb

def attend 
    @event = Event.find(params[:id]) 
    current_user.events << @event 
    redirect_to @event, notice: 'You have promised to attend this event.' 
    end 

    def withdraw 
    # I can't get this to work 
    redirect_to @event, notice: 'You are no longer attending this event.' 
    end 

모델/event.rb

class Event < ActiveRecord::Base 
    attr_accessible :name, :location 
    belongs_to :users 

    has_many :attendees, :dependent => :destroy 
    has_many :users, :through => :attendees 

모델/user.rb

class User < ActiveRecord::Base 
    has_many :events 

    has_many :attendees, :dependent => :destroy 
    has_many :events, :through => :attendees 

모델/attendee.rb

class Attendee < ActiveRecord::Base 
    belongs_to :event 
    belongs_to :user 

    attr_accessible :user_id, :event_id 

    # Make sure that one user cannot join the same event more than once at a time. 
    validates :event_id, :uniqueness => { :scope => :user_id } 

end 

답변

5

난 당신이 문제가 참석자를 찾는 데있어 가정합니다.

def withdraw 
    event = Event.find(params[:id]) 
    attendee = Attendee.find_by_user_id_and_event_id(current_user.id, event.id) 

    if attendee.blank? 
    # handle case where there is no matching Attendee record 
    end 

    attendee.delete 

    redirect_to event, notice: 'You are no longer attending this event.' 
end 
+1

그게 전부입니다! 나는 그것이 사소하다는 것을 알았다. 나는 레일스 (Rails) 나 액티브 레코드 (Active Record)와 같은 메소드를 작성할 수 있다는 것을 잊어 버렸습니까? 그것을 함께 조각 낼 것입니다. 다른 누군가가이 간단한 수정을 유용하게 사용하기를 바랍니다. – Brandt

+0

나는 매우 비슷한 코드를 가지고 있지만 withdraw_event_path (@ event.id)를 찾을 수 없습니다.이 정의되지 않은 메소드 오류를 수정하는 아이디어는 – Marcus

+0

더 좋은 방법이 아닙니까? Attendee.find_by_user_id_and_event_id (current_user.id, event.id)는 못 생겼습니다./ –

관련 문제