I'm making a scheduling app for my small photo business. I'm using Trent Richardson's jQuery TimePicker addon (which extends the jQueryUI dateselect): https://github.com/trentrichardson/jQuery-Timepicker-Addon because time is a critical part of scheduling an assignment.
In order to edit an existing record, I have to provide strftime formatting for the text input field which is tied to the jQuery widget (otherwise the time part won't default to the pre-existing content).
The following works great for creating a new record:
<%= f.input :starts_at, :as => :string %>
The following works great for editing an existing record. Unfortunately, the rails app blows up when I try to create a new record (which doesn't have pre-existing "starts_at" content):
<%= f.input :starts_at, :as => :string, :input_html => { :value => localize(f.object.starts_at, :format => "%m-%d-%Y %I:%M %P") } %>
I can't for the life of me figure out how to test (in the form) for pre-existing content in that field, and thereby offer the formatting or not. I would be so grateful for any suggestions.
Steve
I'm cautiously optimistic. This seems to be working (without the need for a custom input type) for my situation:
<% if @assignment.new_record? %>
<%= f.input :starts_at, :as => :string %>
<% else %>
<%= f.input :starts_at, :as => :string, :input_html => { :value => localize(f.object.starts_at, :format => "%Y-%m-%d %I:%M %P") } %>
<% end %>
Again, with this in the assignments.js.coffee (because it has to match for the jQuery plugin to work):
dateFormat: 'yy-mm-dd',
timeFormat: 'hh:mm tt'
I had been trying to put the condition inline with the f.input statement which failed, and then I tried testing for a value in the :starts_at field, which likewise failed. Testing for whether this is a new record or not seems to be working. For my situation anyway.
The type of the field is probably a DateTime, which means you need to parse the string beforehand. You can do this with setter method or a before_validation filter, for example:
def starts_at=(datetime)
begin
write_attribute(:starts_at, DateTime.strptime(datetime, "%m-%d-%Y %I:%M %P"))
rescue ArgumentError
end
end
def starts_at
begin
self[:starts_at].strftime("%m-%d-%Y %I:%M %P")
rescue NoMethodError
end
end
http://ruby-doc.org/stdlib-2.0/libdoc/date/rdoc/DateTime.html#method-c-parse
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.