繁体   English   中英

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

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

我需要在 Rails 中将持续时间显示为 HH:MM 作为两个 select 框,一个为几小时,另一个为几分钟。 将时间限制为最多 4:00。 “持续时间”(列类型:整数)在数据库中存储为分钟。 我正在使用formtastic。

如果我将输入显示为时间,我可以获得 output 格式的下拉 HH:MM。

"<%= f.input:duration, :label => 'Duration', :as=>:time, :minute_step => 15, :hint=>"以小时为单位", :end => 10 %>"

如何限制选择显示的小时数(小时下拉菜单中只应显示 01、02、03、04)?

请让我知道是否需要为 Rails/Formtastic 指定任何选项。 或者有没有更好的方法来处理这种情况?

我没有看到任何通过 Formtastic 限制它的选项。 您可以将输入显示为 select 并将其明确传递给您想要的选项。

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

然后您可能需要在 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

你可能想看看这个答案,让它们看起来更像原版。

可能有一些更聪明、更快捷的方法来做到这一点,但这是首先想到的。

暂无
暂无

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

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