Lets say I have a model Staff with only two attributes: name and hours.
I have a form like the below, where start and finish are virtual attribute:
<%= form_for(@staff) do |f| %>
<%= f.label :name %><br />
<%= f.text_field :name %>
</div>
<div class="field">
<%= f.label :start %><br />
<%= f.text_field :start %>
<div class="field">
<%= f.label :finish %><br />
<%= f.text_field :finish %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
In my database, I would like to save the name and the hours (hours is the difference between finish and start).
My question is: what is the best approach to calculate and save the hours on my database? There is a way to create a method on the Staff model or I need to do the calculation in the create and in the update actions of my controller?
The proper way is to do it in your model and make a
before_saveor abefore_createcallback. Try something like this :Hope this helps.