0

I have start_time:timestamps and finish_time:timestamps fields in events table. So I want to store here only hours and minutes.

_form.html.erb

<%= f.time_select :start_time_string %>

I added virtual attributes to my model.

event.rb

  # Generates methods: start_time_string, finish_time_string
  #
  [:start_time, :finish_time].each do |field_name|
    define_method("#{field_name}_string") do
      self.send(field_name).strftime('%H:%M') if self.send(field_name)
    end
  end

  [:start_time, :finish_time].each do |field_name|
    define_method("#{field_name}_string=") do |time|
      self.send(field_name) = time.strftime('%H:%M')
    end
  end

But I got error:

syntax error, unexpected '=', expecting keyword_end self.send(field_name) = time.strftime('%H:%M') ^

Why this is happening? Could you please propose a better solution for me if it's possible?

Mike Andrianov
  • 3,033
  • 3
  • 23
  • 24

2 Answers2

1

Replace

[:start_time, :finish_time].each do |field_name|
    define_method("#{field_name}_string=") do |time|
      self.send(field_name) = time.strftime('%H:%M')
    end
  end

with

[:start_time, :finish_time].each do |field_name|
    define_method("#{field_name}_string=") do |time|
      self.send("#{field_name}_string=",time.strftime('%H:%M'))
    end
end

EDIT

This will create two methods start_time_string= and finish_time_string=.

You can call these as,

start_time_string = Time.now
finish_time_string = Time.now
Kirti Thorat
  • 52,578
  • 9
  • 101
  • 108
1

@Kirti's answer is correct.

However your error lies in another the fact that your time_select field is not a Time field in your database.

See this related question, there are many suggested solutions.

Community
  • 1
  • 1
Agis
  • 32,639
  • 3
  • 73
  • 81
  • A little bit earlier I setted `time` type for my `start_time:time` column. But after that not only time was stored in database but year, month, day too. So I found same problem here: http://stackoverflow.com/questions/3682991/ruby-on-rails-time-now. One of the suggestions is to change column type to `timestamps`. – Mike Andrianov Mar 05 '14 at 23:16
  • Yes, use `:datetime` or `:timestamp`. – Agis Mar 05 '14 at 23:20