开发者

Can't display converted units in nested form

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 su开发者_StackOverflow社区re 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.


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 %>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜