开发者

In Rails/Formtastic how do I restrict hours in the time input field

I have a requirement to display duration as HH:MM in Rails as two select boxes one for hours and other for minutes. Restrict the hours to max of 4:00. 'duration'(column type:integer) is stored as minutes in database. And I am using formtastic.

If I dispaly input as time, I am able to get the output format as drop down HH:MM.

"<%= f.input :duration, :label => 'Duration', :as=>:time, :minute_step => 15, :hi开发者_JAVA技巧nt=>"Measured in hours", :end => 10 %>"

How do I restrict the hours shown for selection( only 01, 02, 03, 04 should be displayed in the drop down for hours)?

Please let me know if there are any options to be specified for Rails/Formtastic. Or is there any better way to handle this scenario?


I don't see any options to limit it through Formtastic. You could just display the input as a select and pass it the options you want explicitly.

<%= f.input :hours, :as=>:select, :collection => (0..4) %>
<%= f.input :minutes, :as=>:select, :collection => [0,15,30,45] %>

Then you'll probably need to add these virtual attributes in the model:

before_save :set_duration

def set_duration
  self.duration = @hours * 60 + @minutes
end

def hours
  self.duration / 60;
end

def minutes
  self.duration % 60;
end

def hours=(h)
  @hours = h
end

def minutes=(m)
 @minutes = m
end

def duration=(d)
  @hours = d / 60
  @minutes = d % 60
  self.set_duration
end

And you might want to look at this answer to get them to look more like the original.

There might be some clever, quicker way to do this, but this is the first thing that comes to mind.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜