I'm stumped on my Rails app. I've created 3 models: user, event, category
that have the following associations:
class User
has_many :events, :dependent => :destroy
attr_accessible :name, :email, :password, :password_confirmation, :remember_me
class Category
attr_accessible :name
has_many :events
class Event
attr_accessible :address, :cost, :date, :details, :end_time, :fav, :start_time, :title, :venue
belongs_to :user
belongs_to :category, :foreign_key => :name #not sure if this foreign key is working
The idea is that Users
create events
that are filed under a single category
. The categories are pre-populated so users don't get to make them, only choose which to file under.
My user and events association has been working for a while, but since I've added the category model I get a "Can't mass-assign protected attributes: category" error when I try to create a new event.
I've been browsing pages all day and can't seem to track the error down. I tried adding a foreign key using belongs_to :category, :foreign_key => :name
in the Event
class but that didn't seem to help.
Would graciously appreciate any help, solutions, and/or pointers in the right direction!
Edit 2: I'm pretty new at Rails, but I think I've tracked down where the problem is from the error screen. Says "ActiveModel::MassAssignmentSecurity::Error in EventsController#create" and further down says "app/controllers/events_controller.rb:58:in create" which equates to this line of code: @event = current_user.events.new(params[:event])
.
If I'm reading it correctly, that would mean the error occurs because I'm trying to create a new event with a category
param passed in the hash and it doesn't know what to do with it. Unfortunately, I don't know what to do either...
Edit 3: As requested, here's the Event controller's create action:
def create
@event = current_user.events.new(params[:event])
respond_to do |format|
if @event.save
format.html { redirect_to @event, notice: 'Event was successfully created.' }
format.json { render json: @event, status: :created, location: @event }
else
format.html { render action: "new" }
format.json { render json: @event.errors, status: :unprocessable_entity }
end
end
end