views:

953

answers:

2

I'm working a project that has recurring, weekly events. Thus, I use several DateTime fields in a nontraditional way. What I'm working on is a FormBuilder that creates a field that outputs a select for a weekday, and a select for time. I'm using a twelve-hour plugin I found online, so that works:

class ActionView::Helpers::FormBuilder
  def dow_time(dow,time,options={})
    rval = select(dow, DateTime::DAYNAMES)
    rval += time_select(time, {:minute_step => 15, :ignore_date => false, :twelve_hour => true})
  end
end

The problem I'm having is that the weekday select doesn't actually have a default selected value. This works fine on my create pages, but not on the edit pages. dow is a symbol that references the field in the calling model where the day of the week string is "Monday", "Tuesday", etc. How can I pull that value out of the calling model using dow.

self[dow]

Doesn't work since this is in a different class.

Any ideas? Something different?

A: 

This should work for you ...

class ActionView::Helpers::FormBuilder
  def dow_time(dow_model, time, options={})
    rval = select(dowmodel, :dow, DateTime::DAYNAMES)
    rval += time_select(time, {:minute_step => 15, :ignore_date => false, :twelve_hour => true})
  end
end
Ahsan Ali
self.read_attribute fails with:undefined method `read_attribute' for #<ActionView::Helpers::FormBuilder:0xb6729f3c>"modelinstance" doesn't work because the model is variable, or maybe I'm misunderstanding what you're saying.
Stefan Mai
I've edited the code. Call it with: <%=dow_time(@mymodel, time, etc ...)%>
Ahsan Ali
+2  A: 

If you're inside a FormBuilder, then you can access the current object by simply using the 'object' variable.

Ex:

In: edit.html.erb

<% form_for(@event) do |form| %>
  <%= form.custom_datetime_select(:event_starts_at) %>
<% end %>

In your FormBuilder

def custom_datetime_select(field, options = {})
  start_time = object.send(field)
  ...
end

Both object and object_name are set for you when you call form_for.

See actionpack/lib/action_view/helpers/form_helper.rb for more details.

Kenny C
You win, that's just what I'm looking for. Thanks!
Stefan Mai