BillyBib BillyBib - 4 months ago 22
Ruby Question

Building an RSVP system in Rails with has_many, through

I have an Events app in Rails 5 and I'm trying to build an RSVP system.

The functionality that I'm trying to build is that a user can go to the events show page and click an 'rsvp' button. This user will then show up in the events show page under 'users attending this event'. Additionally, the event will also show up on the user's show page - 'this user is attending the following events'.

I'm pretty new to Rails and I'm not really sure how to handle the rsvp button functionality. This is my code so far:

user.rb

class User < ApplicationRecord
...
has_many :attendances
has_many :events, through: :attendances
...
end


event.rb

class Event < ApplicationRecord

has_many :attendances
has_many :users, through: :attendances

end


attendance.rb

class Attendance < ApplicationRecord
belongs_to :user
belongs_to :event
end


routes.rb

Rails.application.routes.draw do
root 'events#index'

resources :events do
resources :users
end

resources :users
end


And this is the form on the events show page where I'm trying to add a user to the event

show.html.erb - events

<%= form_for([@event, @event.users.build] do |f| %>
<%= f.hidden_field :user_id, value: current_user.id %>
<%= f.submit "RSVP", class: "btn btn-default" %>
<% end %>


Please let me know if you need any extra code posting.

Answer

from your controller's action find the event and and add the user into the attendance simple as

event = Event.find_by_id(params[:event_id])
user = User.find_by_id(params[:user_id])
attendance= event.attendances.create(user_id=>user.id) 

and when you want to know the users who are going for the event you can find as:

users = event.users