【问题标题】:Rails has_many :through association. Remove an association with a link?Rails has_many:通过关联。删除与链接的关联?
【发布时间】:2012-07-09 09:14:47
【问题描述】:

我有一个事件模型和一个通过参加者模型连接的用户模型。我已经弄清楚如何以经过身份验证的用户身份“参加”活动。但我想不通的是一种从活动中“退出”的好方法。我敢肯定这是我错过的一些微不足道的事情,但是有什么比问一些微不足道的问题更好的方法来进入 StackOverflow 呢?哦,我已经搜索了几个小时的 railscasts 和 SO...

谢谢!

views/events/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

models/event.rb

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

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

models/user.rb

class User < ActiveRecord::Base
    has_many :events

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

models/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

【问题讨论】:

    标签: ruby-on-rails ruby activerecord has-many-through


    【解决方案1】:

    我假设您在查找与会者时遇到了麻烦。

    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
    

    【讨论】:

    • 就是这样!我知道这是微不足道的。我忘了你可以写出这样的方法和 Rails 或 Active Record?会把它拼凑起来。我希望其他人会发现这个简单的修复很有用。
    • 我有非常相似的代码,但我找不到withdraw_event_path(@event.id) - 关于修复这个未定义方法错误的任何想法
    • 没有更好的办法吗? Attendee.find_by_user_id_and_event_id(current_user.id, event.id) 看起来很丑:/
    • @FlorianWidtmann 是的,它很丑。 :-) 它在 Rails 4 中也被弃用了。你可以使用Attendee.find_by(user_id: current_user.id, event_id: event.id)
    猜你喜欢
    • 2012-05-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-27
    相关资源
    最近更新 更多