2012-07-09 219 views
4

我有一个通过参加者模型加入的事件模型和用户模型。我已经想出了如何“参加”一个事件作为一个认证用户。但我无法弄清楚的是从事件中“退出”的好方法。我敢肯定,这是微不足道的,我错过了,但有什么更好的方式来进入StackOverflow比问一些微不足道的东西?哦,我一直在寻找railscasts和SO几小时...Rails 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 2012-07-09 22:59:55

+0

我有非常相似的代码,但我找不到withdraw_event_path(@ event.id) - 任何想法修复这个未定义的方法错误 – Marcus 2014-01-13 02:07:45

+0

有没有更好的办法? Attendee.find_by_user_id_and_event_id(current_user.id,event.id)看起来很难看:/ – 2014-03-06 08:04:33