This post is just
about as short and simple as it gets. I'm working on an application
that will support scheduling, meetings and calendars for users across
multiple timezones. So, one of the things that I'm going to need to
track is what timezone the user works in. This will require adding a
timezone attribute to the user's profile record. It's probably worth
noting that you could also add this attribute to a User record rather
than a Profile record if that's where you want to keep your
configuration.
So here we go, three
simple steps.
Step 1: Add the
column to my profile table with the following generated migration:
rails g migration
AddTimezoneToProfiles timezone:string
and execute the
migration with:
rake db:migrate
Step 2: Add the new
field to my existing profile edit page:
<%=
form_for(@profile) do |f| %>
...
<div
class="field">
<%= f.label
:timezone %><br>
<%=
f.time_zone_select(:timezone, ActiveSupport::TimeZone.us_zones) %>
</div>
…
<% end %> //
form_for
Note the use of the
time_zone_select helper and the ActiveSupport::TimeZone.us_zones
method to push most of the work off to Rails.
Step 3: Allow the
controller to accept the timezone field.
def profile_params
params.require(:profile).permit( :address, … , :timezone)
end
And that's it. My
form now allows the user to select their timezone preference and
stores it on their profile record.
No comments:
Post a Comment