虚拟模型和 form_for (或 formattastic)
有时我们需要没有模型创建的表单 - 例如搜索字段或电子邮件,应在其中发送一些说明。创建此表单的最佳方法是什么?我可以创建虚拟模型或类似的东西吗?我想使用 formattastic,但不想使用 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
首先,Formtastic 并不在所有情况下都需要模型,尽管它确实效果最好并且需要更少的模型代码。
就像 Rails 自己的内置
form_for
一样,您可以传入符号而不是对象作为第一个参数,Formtastic 将构建表单并根据符号发布参数。例如:这将使表单值作为
params[:session]
可供控制器使用。其次,模型并不意味着ActiveRecord模型。我的意思是,Formtastic 将与像 ActiveRecord 模型一样嘎嘎的类的任何实例一起工作。
一个典型的例子是许多人正在使用 Authlogic 与 Formtastic 进行身份验证。 Authlogic 的一部分是 UserSession 模型的思想,它工作得很好:
控制器:
表单:
这将使您的表单数据在控制器中以
params[:user_session]
的形式可用。创建一个模型实例来包装模型的关注点确实并不难。只要继续实施 Formtastic 所期望的方法,直到它发挥作用!
Firstly, Formtastic doesn't need a model in all cases, although it certainly works best and requires less code with a model.
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:This will make the form values available to your controller as
params[:session]
.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.
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:
Controller:
Form:
This will make your form data available in your controller as
params[:user_session]
.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!
default_language.rb
foo_controller.rb
index.erb
当值更改时,我使用 AJAX 来发布表单。
default_language.rb
foo_controller.rb
index.erb
I used AJAX to post the form when the value changed.
或者您只需使用 form_for 创建一个表单并将模型引用留空。
例如
<% form_for "", :url=>some_url do |f| %>
<%= f.text_field "some_attribute" %>
<%= Submit_tag "submit" %>
您只需在控制器中输入 params[:some_attribute] 即可获取值。
Or you simply create a form with form_for and leave the model reference blank.
for example
<% form_for "", :url=>some_url do |f| %>
<%= f.text_field "some_attribute" %>
<%= submit_tag "submit" %>
You can fetch the values by simply saying params[:some_attribute] in your controller.