Here's the thing. I have Users and Events and I want to have invitations between them. That is a User can invite another to an Event.
I created an Invitations controller and model. The model looks like this
user_id: (user being invited), event_id:(event_to_attend), inviter: (sent_the_invite)
I'm building my invitations from the controller by going to /invitations/new and submitting a form but I can't get them to work. They were created before but I made some changes and they don't create, they just say "Invitation has been sent" but no invitation is created in the console or anything.
I know they work because in the console I do
a=User.first
a.invitations.build(event_id: 1, inviter:2)
a.save
And then I can see the invitation and the user_id is the one who created the invitation, a in this case I can see the invitation and can get the user by calling the .invitees method in Event. So the associations work. But I can't create it through the form.
Here's the form
<%= form_for(@invitation) do |f| %>
<% userArray=User.all.select{|u| u.name unless u==current_user }%>
<% names=userArray.map{|u| u.name} %>
<% events=current_user.attended_events.map{|u| u.description} %>
<%= f.label :event %>
<%= f.select :event, events %>
<%= f.label :user %>
<%= f.select :user, names %>
<%= f.submit "Send" %>
<% end %>
I use only name of user and description of event for UX
Here's my invitations controller
class InvitationsController < ApplicationController include ApplicationHelper def new @invitation=Invitation.new end
def create #Not taking into account, duplicate users, and events with the same name by the same user.
#user being invited
@user=User.find_by(name: params[:invitation][:user])
#event being invited to
@event=Event.find_by(description: params[:invitation][:event])
#Inviter is current user, invitee is @user
@user.invitations.build(event_id: @event.id, inviter: current_user.id)
#Event not in user.attended_events
if !(@user.attended_events.where(id: @event.id) || \
@user.invitations.where("[email protected] AND [email protected]") )
flash.now[:danger]="User is already going to the event"
render 'foo'
#render 'new'
elsif @user.save!
flash[:success]="Invitation was SENT!"
redirect_to new_invitation_path
else
flash.now[:danger]="Please select both options"
render 'foobar'
#render 'new'
end
end