I have an Event model and a Notifications model. An event has many notifications, and a notification only has one event. My notification object has two attributes: message and event_id. When I build a new notification, how can I set the event_id to the current event's id?
events_controller.rb
class EventsController < ApplicationController
before_action :signed_in, only: [:new,:create]
def new
@event = Event.new
end
def create
@event = Event.new(event_params)
if @event.save
flash[:success] = "Your Event has been created."
redirect_to root_path
else
render 'new'
end
end
def show
@event = Event.find(params[:id])
@notification = @event.notifications.build
respond_to do |format|
format.html
format.xml { render :xml => @event }
format.json { render :json => @event }
end
end
private
def event_params
params.require(:event).permit(:name, :description)
end
def signed_in
unless user_signed_in?
redirect_to new_user_session_path
flash[:warning] = "You must be signed in to access that page"
end
end
end
notifications_controller.rb
class NotificationsController < ApplicationController
def create
@notification = Notification.new(notification_params)
if @notification.save
redirect_to root_path
flash[:success] = "Your message has been sent"
else
render 'new'
end
end
def show
end
private
def notification_params
params.require(:notification).permit(:message, :event_id)
end
def signed_in
unless user_signed_in?
redirect_to new_user_session_path
flash[:warning] = "You must be signed in to access that page"
end
end
end
routes.rb
devise_for :users
resources :events
resources :notifications
root 'static_pages#home'
match '/help', to: 'static_pages#help', via: 'get'
match '/about', to: 'static_pages#about', via: 'get'
match '/contact', to: 'static_pages#contact', via: 'get'
@notification = @event.build_notification(notification_params)