我有一个嵌入式mongoid类“Option”,我想用以下方式初始化:
@option = @ event.options.new('yes')
class Option
include Mongoid::Document
field :content, type: String
embedded_in :event
def initialize(content)
@content = content
end
end
所以我在上面添加了构造函数,但是我收到以下错误:
EventsController中的NoMethodError #new undefined method` []'for 零:NilClass
我错过了什么?
使用rails 4 ...
编辑:这里要求的是控制器代码:
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
答案 0 :(得分:1)
这是因为您的field :content, type: String
尚未初始化
您需要在super()
方法的第一行调用initialize
,然后您才能在构造函数中更改content
的值
尝试:
def initialize(content)
super()
self.content = content
end