Ruby-on-rails formtastic - 如何使用值预填充字符串输入

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2044497/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 22:07:47  来源:igfitidea点击:

formtastic - how to prepopulate a string input with a value

ruby-on-railsformtastic

提问by ernd enson

I'm building an app, where users can give comments by just leaving their email to the comment.

我正在构建一个应用程序,用户可以在其中通过将电子邮件留在评论中来发表评论。

I want them to be able to register directly from there, by a link with their email adress as a param
(like: <%= link_to register_path(:email => @comment.email %>) - so there is no existing user record yet.
this should be done by applying a value to the form.inputfield via the :valueoption.

我希望他们能够直接从那里注册,通过将他们的电子邮件地址作为参数的链接
(例如:)<%= link_to register_path(:email => @comment.email %>- 所以还没有现有的用户记录。
这应该form.input通过:value选项将值应用于字段来完成。

But the following code doesn't work!

但是下面的代码不起作用!

<%- if params[:email] -%>
  <%= f.input :email, :required => true, :value => params[:email] %>
<%- else -%>
  <%= f.input :email, :required => true %> 
<%- end -%>

I had a look inside the formtastic rdocand inside my local gem but couldn't find any option for that.

我查看了formtastic rdoc和本地 gem 内部,但找不到任何选项。

Suggestions anyone?

任何人的建议?

回答by Justin French

Yup, you got the right answer all by yourself! Formtastic's rdoc is a mess, but we're working on it. Another option if you want this purely at a view level is to use the :input_htmloption, which gives you direct access to HTML attributes of the input tag:

是的,你自己得到了正确的答案!Formtastic 的 rdoc 一团糟,但我们正在努力。如果您只想在视图级别进行此操作,另一种选择是使用该:input_html选项,它使您可以直接访问输入标签的 HTML 属性:

f.input :email, :input_html => { :value => params[:email] }

回答by ernd enson

sometimes the easiest things come to your mind by asking for them:

有时,通过询问您会想到最简单的事情:

approach: do the job in the controller not the view!

方法:在控制器而不是视图中完成工作!

if params[:email]
  @user = User.new(:email => params[:email])
else
  @user = User.new
end

sorry for bothering you!

对不起,打扰你!