我对 ruby/rails/POO 有点陌生,我对我正在意识到的一种形式有点迷失。我正在使用 gem formtastic,我正在使用 haml。
我有这个模型
class Help < ActiveRecord::Base
attr_accessible :answer, :category, :question
validates :category, presence: true, uniqueness: true
validates :question, presence: true
validates :answer, presence: true
end
在我的表单中,我希望能够创建一个带有其类别的新问题/答案。应该在选择框中选择类别,但如果我想要的类别尚未列出,我希望能够添加它。
这是表格
= semantic_form_for @help do |f|
= f.inputs do
= f.input :category, :as => :select, :collection => Help.category
= f.input :category
= f.input :question
= f.input :answer
= f.action :submit, :as => :button
编辑 :
class HelpsController < ApplicationController
# GET /helps
# GET /helps.json
def index
@helps = Help.all.sort_by {|f| f.category}
respond_to do |format|
format.html # index.html.erb
format.json { render json: @helps }
end
end
# GET /helps/1
# GET /helps/1.json
def show
@help = Help.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.json { render json: @help }
end
end
# GET /helps/new
# GET /helps/new.json
def new
@help = Help.new
respond_to do |format|
format.html # new.html.erb
format.json { render json: @help }
end
end
# GET /helps/1/edit
def edit
@help = Help.find(params[:id])
end
# POST /helps
# POST /helps.json
def create
@help = Help.new(params[:help])
respond_to do |format|
if @help.save
format.html { redirect_to @help, notice: 'Help was successfully created.' }
format.json { render json: @help, status: :created, location: @help }
else
format.html { render action: "new" }
format.json { render json: @help.errors, status: :unprocessable_entity }
end
end
end
# PUT /helps/1
# PUT /helps/1.json
def update
@help = Help.find(params[:id])
respond_to do |format|
if @help.update_attributes(params[:help])
format.html { redirect_to @help, notice: 'Help was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: "edit" }
format.json { render json: @help.errors, status: :unprocessable_entity }
end
end
end
# DELETE /helps/1
# DELETE /helps/1.json
def destroy
@help = Help.find(params[:id])
@help.destroy
respond_to do |format|
format.html { redirect_to helps_url }
format.json { head :no_content }
end
end
end
当我尝试访问 /help/new 时,它实际上对我说:
NilClass:Class 的未定义方法“model_name”
目的是在选择框中拥有已经注册的类别,如果用户没有在选择框中创建他想要使用的类别,他可以通过在输入中键入来创建一个。
有什么线索可以帮助我这样做吗?
亲切地,罗伯