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??
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
I haven't tested this exactly, but I think what you're looking for is this:
#in the Event Model
validates :users, uniqueness: true
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.