There is probably a reeeeeally obvious answer to this, but I can’t find it, so:
I have a timesheets model that has many time_entries, added via a nested form:
timesheets edit.html.erb:
<%= form_for @timesheet do |f| %>
.
.
.
<%= f.fields_for :time_entries do |builder| %>
<%= render 'time_entry_fields', :f => builder %>
<% end %>
time_entry_fields partial
<%= f.text_field :project %>
<%= f.text_field :day1_hours %>
<%= f.text_field :day2_hours %>
<%= f.text_field :day3_hours %>
<%= f.text_field :day4_hours %>
<%= f.text_field :day5_hours %>
<%= f.text_field :day6_hours %>
<%= f.text_field :day7_hours %>
I’d like to define a method that shows the sum of all the entered hours – day1_hours + day2_hours + ... etc. I tried putting this in the model:
time_entry.rb
def total_hours
d1 = day1_hours || 0
d2 = day2_hours || 0
d3 = day3_hours || 0
d4 = day4_hours || 0
d5 = day5_hours || 0
d6 = day6_hours || 0
d7 = day7_hours || 0
d1 + d2 + d3 + d4 + d5 + d6 + d7
end
And it works just fine if I call it on a TimeEntry object in the console:
1.9.3p0 :003 > TimeEntry.find(3).total_hours
TimeEntry Load (0.3ms) SELECT "time_entries".* FROM "time_entries" WHERE "time_entries"."id" = $1 LIMIT 1 [["id", 3]]
=> 8
But I can’t figure out how to call it from within the time_entry_fields partial in the form. I would normally be able to define @time_entry in the controller so that I could use @time_entry.total_hours, but how do you do this for an object in a nested form?
f.object.total_hoursin your partial should be what you want