BillyBib BillyBib - 1 year ago 82
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:


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


class Event < ApplicationRecord

has_many :attendances
has_many :users, through: :attendances



class Attendance < ApplicationRecord
belongs_to :user
belongs_to :event


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

resources :events do
resources :users

resources :users

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,] do |f| %>
<%= f.hidden_field :user_id, value: %>
<%= f.submit "RSVP", class: "btn btn-default" %>
<% end %>

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

Answer Source

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=> 

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

users = event.users
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download