简体   繁体   English

在表单提交Rails之前如何处理文本输入数据

[英]How to process text input data before form submit ruby on rails

I'm using rails form helper to generate form and retrieve data from users. 我正在使用Rails表单帮助程序来生成表单并从用户检索数据。 like this 像这样

<div class="controls">
  <%= f.text_field :duration, class: "input-large" %>
</div>

however,I need this input, before its store to database 'duration' column,multiply by 10. I have search about this and try implement a method,create a function,which multiply the value,and call it under before_save 但是,我需要此输入,然后将其存储到数据库“ duration”列中,然后乘以10。我已对此进行搜索并尝试实现一个方法,创建一个函数,将值相乘,然后在before_save下调用它

before_save  :multiply_ten, on: [ :create,:update ]

problem is,i'm not only updating this column using web page form,and also by http request send by device.by implementing this I multiply all value by 10,But I only want the web form input part multiply 10. is there a way to do it in form css or have other tricks? 问题是,我不仅要使用网页表单来更新此列,还要通过设备发送的http请求来更新。通过实现这一点,我将所有值都乘以10,但是我只希望Web表单输入部分乘以10。形式的CSS或其他技巧的方式吗? thanks 谢谢

There a multiple ways to achieve what you're looking for. 有多种方法可以满足您的需求。 Since you only want to multiply duration by 10 in the case of a particular web form, I would suggest doing the multiplication at the controller level, or even at the view level, instead of at the model level. 由于在特定Web表单的情况下,您只想将持续时间乘以10,因此我建议在控制器级别甚至视图级别而不是模型级别进行乘法。

You could have your view modify the http params before the request is made via javascript. 您可以在通过javascript发出请求之前,先修改视图的http参数。

Or, if you'd prefer to do it at the controller level, you need a way to communicate to the controller that the submitting form is in fact the one requiring the multiplication. 或者,如果您希望在控制器级别执行此操作,则需要一种与控制器进行通信的方式,即提交表单实际上就是需要乘法的表单。 Example: 例:

First, in your view, add an extra parameter via hidden input indicating that the form needs a multiplication of 10: 首先,在您的视图中,通过隐藏输入添加一个额外的参数,指示表单需要乘以10:

<%= hidden_field_tag :special_form, true %>

Then, in your controller, before you assign attributes to a new object to be saved, modify the params if params[:special_form] exists: 然后,在控制器中,在将属性分配给要保存的新对象之前,如果params[:special_form]存在,请修改参数:

params[:duration] = params[:duration].to_f * 10 if params[:special_form].present?

Hope this helps! 希望这可以帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM