问题描述
有时,我们需要不创建模型的表单-例如搜索字段或电子邮件,应在其中发送一些说明.创建此表单的最佳方法是什么?我可以创建虚拟模型或类似的东西吗?我想使用formtastic,而不是form_tag.
Sometimes we need form without model creation - for example search field or email, where should be send some instructions. What is the best way to create this forms? Can i create virtual model or something like this? I'd like to use formtastic, but not form_tag.
推荐答案
首先,Formtastic并不一定在所有情况下都需要模型,尽管它肯定是最好的,并且模型所需的代码更少.
Firstly, Formtastic doesn't need a model in all cases, although it certainly works best and requires less code with a model.
就像Rails内置的form_for
一样,您可以传入符号而不是对象作为第一个参数,Formtastic将构建表单并根据该符号发布参数.例如:
Just like Rails' own built-in form_for
, you can pass in a symbol instead of an object as the first argument, and Formtastic will build the form and post the params based on the symbol. Eg:
<% semantic_form_for(:session) do |f| %>
...
<% end %>
这将使表单值作为params[:session]
供您的控制器使用.
This will make the form values available to your controller as params[:session]
.
第二,模型并不表示 ActiveRecord 模型.我的意思是,Formtastic可以与任何像ActiveRecord模型一样发出 quacks 的类的实例一起工作.
Secondly, a model doesn't mean an ActiveRecord model. What I mean is, Formtastic will work with any instance of a class that quacks like an ActiveRecord model.
许多人们使用Authlogic进行Formtastic身份验证的经典示例. Authlogic的一部分是UserSession模型的想法,它可以正常工作:
A classic example of this that many people are using Authlogic for authentication with Formtastic. Part of Authlogic is the idea of a UserSession model, which works fine:
控制器:
def index
@user_session = UserSession.new
end
表格:
<% semantic_form_for(@user_session) do |f| %>
<%= f.input :login %>
<%= f.input :password %>
<% end %>
这将使您的表单数据作为params[:user_session]
在控制器中可用.
This will make your form data available in your controller as params[:user_session]
.
真的很难创建一个模型实例来包装您的模型问题.只需继续执行Formtastic期望的方法,直到您开始工作即可!
It's really not that hard to create a model instance to wrap up the concerns of your model. Just keep implementing the methods Formtastic is expecting until you get it working!
这篇关于虚拟模型和form_for(或formtastic)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!