I'm using rails form helper to generate form and retrieve data from users. 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
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? 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.
You could have your view modify the http params before the request is made via javascript.
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:
<%= 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[:duration] = params[:duration].to_f * 10 if params[:special_form].present?
Hope this helps!