防止用户两次提交同一事件

时间:2016-08-10 20:55:31

标签: ruby-on-rails activerecord

我目前有一个用户模型和一个事件模型。现在,当前用户可以"提交"参加活动。如果用户单击button_tag,该方法基本上会将事件推送给用户。我试图弄清楚如何阻止用户两次提交相同的事件。有一个简单的检查,我不知道??

控制器

  class EventsController < ApplicationController
  before_action :authenticate_user!

  def index
    @event = Event.all
  end

  def commit
    @event = Event.find(params[:id])
    current_user.events << @event
    redirect_to root_path
    flash[:success] = "You have successfully commited to this event!"
  end
end

表格

 <% @event.each do |event| %>
  <h3>
    <%= event.name %>
  </h3>
  <p>
    <%= event.description %>
  </p>
  <%= button_to "Commit", commit_event_path(event.id)  %>
<% end %>

活动模型

class Event < ActiveRecord::Base
  has_and_belongs_to_many :users
  geocoded_by :address
  after_validation :geocode
  validates :name, presence: true
  validates :description, presence: true
  validates :full_street_address, presence: true
  validates :city, presence: true
  validates :zip, presence: true
  validates :state, presence: true

  def address
    [city, state, zip, full_street_address].compact.join(', ')
  end
end

用户模型

class User < ActiveRecord::Base
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable, :confirmable,
         :recoverable, :rememberable, :trackable, :validatable

  has_and_belongs_to_many :events 
end

1 个答案:

答案 0 :(得分:0)

我还没有完全测试过,但我认为你正在寻找的是:

#in the Event Model
validates :users, uniqueness: true
相关问题