ruby-on-rails - Rails has_many :through association. 删除与链接的关联?

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

我有一个事件模型和一个通过参加者模型连接的用户模型。我已经弄清楚如何以经过身份验证的用户身份“参加”事件。但我想不通的是从事件中“退出”的好方法。我敢肯定这是我遗漏的一些微不足道的事情,但是有什么比询问一些微不足道的事情更好的进入 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

最佳答案

我假设您在寻找与会者时遇到了问题。

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

关于ruby-on-rails - Rails has_many :through association. 删除与链接的关联?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11404094/

相关文章:

ruby-on-rails - 在 Windows 上创建 Rails 项目时出现 Sqlite 错误

ruby - 使用作为字符串存储在数组中的数学符号

ruby - 解析文本文件行

ruby - 如何在 ruby​​ Sinatra 中使用 strftime 本地化日期名称

mysql - 无法连接到 'myhost.com' 上的 MySQL 服务器 (4)

ruby-on-rails - Slim 语法错误

ruby-on-rails - 如何让 Rspec2 支持不同路径中的模型和规范?

ruby-on-rails - 删除多个图像事件存储阵列中的单个图像

mysql - 如何从两个表中查询数据并按日期排序? (事件记录)

ruby-on-rails - 如何使用 ActiveRecord 映射多个属性?