I'm coding a project from "The Odin Project" about Rails Associations. I thought I had get the topic pretty well, but I hit a block.
I'm getting a NoMethodError in EventsController#new // Undefined method 'created_events' for nil:NilClass
Here's my User Model:
class User < ApplicationRecord
has_secure_password
has_many :created_events, :foreign_key => :creator_id, :class_name => 'Event', :dependent => :destroy
end
Event Model:
class Event < ApplicationRecord
belongs_to :creator, :class_name => 'User'
end
EventsController:
class EventsController < ApplicationController
def index
@events = Event.all
end
def show
@event = Event.find(params[:id])
end
def new
@user = User.find_by_email(params[:email])
@created_event = @user.created_events.build
end
def create
@user = User.find_by_email(params[:email])
@created_event = @user.created_events.build(event_params)
if @created_event.save
flash[:notice] = "Event was successfully created!"
redirect_to @created_event
else
render 'new'
end
end
private
def event_params
params.require(:event).permit(:name, :location, :date, :description)
end
end
And my 'new' view, which I'm not sure it's 100% correct given I've messed with it a bit.
<h1>New Event</h1>
<%= form_for @created_event do |f| %>
<p>
<%= f.label :name %><br>
<%= f.text_field :name %>
</p>
<p>
<%= f.label :location %><br>
<%= f.text_field :location %>
</p>
<p>
<%= f.label :date %><br>
<%= f.text_field :date %>
</p>
<p>
<%= f.label :description %><br>
<%= f.text_area :description %>
</p>
<p>
<%= f.submit %>
</p>
<% end %>
For simplicity, I've included the form on the page, although in my project I've it stashed in a partial.
I've tested 'created_events' in the rails console, and it worked but on the site, it gives me the error.
If someone can tell me how to fix this, and what I'm doing wrong it would be much appreciated.
EventsController#newand the error means@userisnil, soUser.find_by_email(params[:email])doesn't return a user. - Michael Kohl