1) entry form contains one field (long text) and submit button;
2) stored in the database (and displayed to the user when viewing) two fields: one - from form, the second - calculated based on the one
how to do?
update: what i do:
1) rails new forstackoverflow
2) cd forstackoverflow/
3) rails generate scaffold Note desc:text word_count:integer
4) vim app/views/notes/_form.html.erb
5) Delete div :
<div class="field">
<%= f.label :word_count %><br>
<%= f.number_field :word_count %>
</div>
6) and i want calculate and save to db word_count, but not know how
Edited
If you are using scaffolding, the params are automatically saved to database when form is submitted, which you do not want.
You will need to require the param in your controller using strong params . Access the param using params[input]
. Apply logic and save separate params to database exclusively in your controller.
The specific method of word_count can be done like this:
string.split.size
So in the model, make sure you have created two attributes, one for the string and one for the result of word_count. For now let us assume that you are using "words" for string, and "word_count" for total words in string.
In your view create a form field labeled "words", which will be sent to the params hash as such: form[words]
.
In the controller under the create action, add the following:
@form.words = params[:form][:words]
@form.word_count = @form.words.split.size
@form.save
Do that in model callback, let's say, before_save
. Here's an example:
class Note < ActiveRecord::Base
before_save do
self.word_count = self.desc.to_s.split.size
# to_s just in case self.desc would be nil
end
end
This way each time the model is saved, it will save new word count.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.