ruby-on-rails – Rails has_many:通过关联.删除与链接的关联?
发布时间:2020-12-17 02:36:37  所属栏目:百科  来源:网络整理 
            导读:我有一个事件模型和一个通过Attendees模型加入的用户模型.我已经想出如何作为经过身份验证的用户“参加”活动.但我无法弄清楚的是从事件“退出”的好方法.我确信这是一件微不足道的事情,我错过了但是有什么更好的方式来进入StackOverflow而不是问一些微不足
                
                
                
            | 
                         
 我有一个事件模型和一个通过Attendees模型加入的用户模型.我已经想出如何作为经过身份验证的用户“参加”活动.但我无法弄清楚的是从事件“退出”的好方法.我确信这是一件微不足道的事情,我错过了但是有什么更好的方式来进入StackOverflow而不是问一些微不足道的事情?哦,我一直在搜索railscasts和SO几个小时…… 
  
  
谢谢! 观点/事件/ 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
解决方法
 我认为你在找到参加者时遇到了麻烦. 
  
  
  
        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
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!  | 
                  
