Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8699309
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 13, 20262026-06-13T01:55:02+00:00 2026-06-13T01:55:02+00:00

I have trawled the API and spent two nights staring at this code and

  • 0

I have trawled the API and spent two nights staring at this code and unfortunately while I sense I’m close to the solution, I can’t quite get it to work. I have a model representing shifts, which among other attributes have a start time.

create_table "shifts", :force => true do |t|
  t.datetime "start"

The user interacts with this as a simple time as the date is set elsewhere, so I have set up virtual accessors to get and set.

class Shift < ActiveRecord::Base
  def start_time
    start.strftime("%H:%M")
  end

  def start_time=(time)
    date = start.midnight
    self.start = add_string_time_to_date(date, time)
  end

  def add_string_time_to_date(date, string_time)
    t = DateTime.strptime(string_time, "%H:%M")
    DateTime.new(date.year, date.month, date.mday, t.hour, t.min)
  end
end

This all works fine when manipulated through a standard controller with @shift.update_attributes(params[:shift]) provided one enters the time in the expected format.

I would like to validate the time format entered but its not as simple as using the method below as strptime() raises an ArgumentError before the validation is reached.

validates :start_time, :format => { :with => /^([0-1][0-9]|[2][0-3]):([0-5][0-9])$|^/, 
  :message => "Invalid format." }

I can work round this by putting a conditional call in start_time() such as the example below, but that doesn’t really work satisfactorily for two reasons.

def start_time=(time)
  if time =~ /^([0-1][0-9]|[2][0-3]):([0-5][0-9])$|^/
    date = start.midnight
    self.start = add_string_time_to_date(date, time)
  else 
    errors.add :start, "format invalid."
    nil
  end
end

First ActiveRecord doesn’t seem to know that the setter has failed. I deduce this from the fact update_attributes() in the controller returns as if all was well, even though it wasn’t. Second, there is no feedback returned to the user, so the call to errors.add is probably out of context. Its also a bit ugly.

The desired functionality is that of a standard validation, so if it fails the user sees an error on the form just as they would with any other validation failure. So in short, how do I achieve this functionality, and am I approaching this in the right way?

Do I need to raise a specific exception in order to notify ActiveRecord of troubles, and if so where is best to do so? It is best just to rescue and use the flash?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-13T01:55:04+00:00Added an answer on June 13, 2026 at 1:55 am

    You should better split the logic of these attributes.

    • First define an attr_accessor for start_time (even if it’s only saved in memory).
    • Then initialize the value accordingly.
    • Finally set the start attribute only when the model is saved.

    This would look like:

    class Shift < ActiveRecord::Base
      attr_accessor :start_time
    
      after_initialize :default_values
      before_save :set_start
    
      def add_string_time_to_date(date, string_time)
        t = DateTime.strptime(string_time, "%H:%M")
        DateTime.new(date.year, date.month, date.mday, t.hour, t.min)
      end
    
      private
    
      def default_values
        self.start_time = start.strftime("%H:%M") if start_time.nil? && start.present?
      end
    
      def set_start
        if self.start_time.present?
           date = start.midnight
           self.start = add_string_time_to_date(date, time)
        end
      end
    
    end
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I've trawled the SO website thinking this is pretty obvious but alas I have
I have trawled the internet for this answer, but alas couldn't find one. In
Jquery wont load. I'm a noob, but have persisted, trawled this site & tried
Have you guys had any experiences (positive or negative) by placing your source code/solution
I have trawled the web and the WebDriver API. I don't see a way
so I have trawled true all threads in here and any where else where
I have followed numerous screen casts as well as trawled the backbone docs extensively
have written this little class, which generates a UUID every time an object of
have a problem. At first look at this HTML <div id=map style=background-image: url(map.png); width:
Have a SQL problem, adding this model all works correctly, the problem is in

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.