简体   繁体   English

在 Rails/Formtastic 中,我如何限制时间输入字段中的小时数

[英]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.我需要在 Rails 中将持续时间显示为 HH:MM 作为两个 select 框,一个为几小时,另一个为几分钟。 Restrict the hours to max of 4:00.将时间限制为最多 4:00。 'duration'(column type:integer) is stored as minutes in database. “持续时间”(列类型:整数)在数据库中存储为分钟。 And I am using formtastic.我正在使用formtastic。

If I dispaly input as time, I am able to get the output format as drop down HH:MM.如果我将输入显示为时间,我可以获得 output 格式的下拉 HH:MM。

"<%= f.input:duration, :label => 'Duration', :as=>:time, :minute_step => 15, :hint=>"Measured in hours", :end => 10 %>" "<%= f.input:duration, :label => 'Duration', :as=>:time, :minute_step => 15, :hint=>"以小时为单位", :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)?如何限制选择显示的小时数(小时下拉菜单中只应显示 01、02、03、04)?

Please let me know if there are any options to be specified for Rails/Formtastic.请让我知道是否需要为 Rails/Formtastic 指定任何选项。 Or is there any better way to handle this scenario?或者有没有更好的方法来处理这种情况?

I don't see any options to limit it through Formtastic.我没有看到任何通过 Formtastic 限制它的选项。 You could just display the input as a select and pass it the options you want explicitly.您可以将输入显示为 select 并将其明确传递给您想要的选项。

<%= 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:然后您可能需要在 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.可能有一些更聪明、更快捷的方法来做到这一点,但这是首先想到的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM