【发布时间】:2015-07-16 10:42:19
【问题描述】:
我已经使用非 db 支持的模型实现了这个简单的表单。而且我能够执行验证并在其上显示表单字段。但我已经使用资源实现了这一点。现在我想了解如何添加更多动作,除了 CRUD 之外,并为它们定义路由。或者,如果我想停止使用resources,并明确定义操作路径。我应该如何处理?
我的文件:
控制器:new_forms_controller.rb
class NewFormsController < ApplicationController
def new
@form = NewForm.new
flash[:notice] = nil
end
def index
end
def create
@form = NewForm.new(params[:new_form])
if @form.valid?
flash[:notice] = "Successfully created recommendation."
render :action => 'show'
else
render :action => 'new'
end
end
def show
end
end
型号:new_form.rb
class NewForm
include ActiveModel::Validations
include ActiveModel::Conversion
include ActiveModel::Naming
attr_accessor :title, :article, :content, :author
validates :title, :article, :content, :author, :presence => true
validates :title, :article => {:minimum => 5 }
def initialize(attributes = {})
attributes.each do |name, value|
send("#{name}=", value)
end
end
def persisted?
false
end
end
路线:route.rb
TestBranch::Application.routes.draw do
resources :new_forms
root :to => "new_forms#new"
end
新视图
<%= content_for :title, "New Form" %>
<% if flash[:notice] %>
<p><%= flash[:notice]%></p>
<% end %>
<%= form_for @form do |f| %>
<% if @form.errors.any? %>
<div id="error_explanation">
<h2>
<%= pluralize(@form.errors.count, "error") %> prohibited
this article from being saved:
</h2>
<ul>
<% @form.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<p>
<%= f.label :titleID %> <br/>
<%= f.text_field :titleID %><br/>
</p>
<p>
<%= f.label :articleID %><br/>
<%= f.text_field :articleID %><br/>
</p>
<p>
<%= f.label :content %><br/>
<%= f.text_field :content %><br/>
</p>
<p>
<%= f.label :author %><br/>
<%= f.text_field :author %><br/>
</p>
<p><%= f.submit "Submit" %></p>
<% end %>
【问题讨论】:
标签: ruby-on-rails ruby ruby-on-rails-3 routes