views:

14

answers:

1

I'm working on an app where I have a user preference to show distances or weights in metric or standard units. I'm using a filter to save the units in a consistent format in the database

before_save :convert_distance

What's the best way to display these units in my views? I tried adding a getter in my model called display_distance like below, but it didn't work.

  #model
  def display_distance
      self.workout.user.uses_metric ? self.distance * 1.609344 : self.distance
  end

  #view
  <%= f.text_field :distance, {:value=>f.object.display_distance} %>

  #error
  You have a nil object when you didn't expect it!

I did a to_yaml and verified that f.object is an instance of the correct object. Also, I'm using nested forms, I'm not sure if that matters.

Also, I'm not sure if I should be trying to do the conversion in the model or in a helper. I thought the model would be better as I'll be using this functionality in multiple views.

A: 

The form does not know anything about your object, you have to pass it in through your controller. You likely have something like this in your controller (assuming this is the edit view):

def edit
  @my_object = MyObject.find(params[:id])
end

Then you can access this in the view like so:

<%= @my_object.display_distance %>
Karl
The problem is it's a nested form, so I'm in one of (potentiall) many children of @my_object. So my initial object is @workout, but I'm inside of a partial called via (workout has many workout_exercises)<% f.fields_for :workout_exercises do |builder| %>
John
How would I access the correct workout_exercise object inside of my partial? I just saw that the fields_for had an object method that seemed to return my object so I used that (sorry I'm really new to Ruby and Rails...)
John
if it is a child of `@my_object`, I assume you have some kind of association set up? Such as `@my_object.child_objects`. That would be how you access information from the child. You can build the form around this by doing something like `@my_object.child_objects.each do |child_object|; fields_for ...; end`. Check out the one-to-many example here: http://api.rubyonrails.org/classes/ActionView/Helpers/FormHelper.html#M002291
Karl