Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails Formbuilder Question

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?

like image 897
Stefan Mai Avatar asked Jun 01 '09 02:06

Stefan Mai


1 Answers

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.

like image 147
kennyc Avatar answered Sep 23 '22 04:09

kennyc