我在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
当我尝试接触/帮助/新时,它实际上对我说:
NilClass的未定义方法`model_name':Class
目的是在选择框中输入已注册的类别,如果用户没有找到他想在选择框中使用的类别,他可以通过在输入中键入来创建一个。
有任何线索可以帮助我这样做吗?
亲切地, 罗布
答案 0 :(得分:1)
试试这个:
= f.collection_select :category
答案 1 :(得分:0)
我发现了一种方法可以实现我想要的一半。
这是方法pluck
。
我在我的模型中定义了一个静态方法:
def self.getcat
Help.pluck(:category)
end
然后在我的表单中简单地在我的集合中调用此方法:
= f.input :category, :as => :select, :collection => Help.getcat