Reputation: 89
I have an emmbedded mongoid class "Option" which I would like to initialize the following way:
@option = @event.options.new('yes')
class Option
include Mongoid::Document
field :content, type: String
embedded_in :event
def initialize(content)
@content = content
end
end
So I added the consctructor above but I get the following error:
NoMethodError in EventsController#new undefined method `[]' for nil:NilClass
What am I missing?
Using rails 4...
EDIT: As requested here is the controller code:
class EventsController < ApplicationController
before_action :set_event, only: [:show, :edit, :update, :destroy]
# GET /events
# GET /events.json
def index
@events = Event.all
end
# GET /events/1
# GET /events/1.json
def show
end
# GET /events/new
def new
@event = Event.new
@event.invitees << @event.invitees.build
@event.options << @event.options.build
#end
end
# GET /events/1/edit
def edit
end
# POST /events
# POST /events.json
def create
# TODO: adapt event_params and filter right
#@event = Event.create(event_params)
@event = Event.new(params[:event])
respond_to do |format|
if @event.save
#TODO: Save users attached to event in user collection
format.html { redirect_to @event, notice: 'Event was successfully created.' }
format.json { render action: 'show', status: :created, location: @event }
else
format.html { render action: 'new' }
format.json { render json: @event.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /events/1
# PATCH/PUT /events/1.json
def update
respond_to do |format|
if @event.update(event_params)
format.html { redirect_to @event, notice: 'Event was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: 'edit' }
format.json { render json: @event.errors, status: :unprocessable_entity }
end
end
end
# DELETE /events/1
# DELETE /events/1.json
def destroy
@event.destroy
respond_to do |format|
format.html { redirect_to events_url }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_event
@event = Event.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def event_params
params.require(:event).permit(:name, :description, :date)
end
end
Upvotes: 0
Views: 112
Reputation: 5306
That is because your field :content, type: String
is not initialized yet
You'll need to call super()
in the first line of your initialize
method, then you'll be able to change the value of content
in the constructor
Try:
def initialize(content)
super()
self.content = content
end
Upvotes: 1