0

I currently have a User model and a Event model. Right now a the current user can "commit" to an event. The method basically pushes the event on the user if they click the button_tag. I'm trying to figure out how to prevent a user from committing the same event twice. Is there a simple check that I'm unaware of??

Controller

  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

Form

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

Event Model

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

User Model

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
Bitwise
  • 8,021
  • 22
  • 70
  • 161

1 Answers1

0

I haven't tested this exactly, but I think what you're looking for is this:

#in the Event Model
validates :users, uniqueness: true
Okomikeruko
  • 1,123
  • 10
  • 22