当我使用帮助
时= f.date_select:date_of_birth
它会产生3个彼此相邻的选择框:
<select id="user_date_of_birth_3i" name="user[date_of_birth(3i)]">...</select>
<select id="user_date_of_birth_3i" name="user[date_of_birth(2i)]">...</select>
<select id="user_date_of_birth_3i" name="user[date_of_birth(1i)]">...</select>
因此,一个Rails助手将创建这3个选择框。 我需要放一个Rails助手,它只会产生一个选择框,如:
= f.date_select:date_of_birth_3i
(但这会产生错误)
会生成
<select id="user_date_of_birth_3i"> name="user[date_of_birth(3i)]">...</select>
和其他两个选择框相同......
有没有办法实现这个目标?
谢谢
答案 0 :(得分:1)
我刚刚提出了一个基于表单标记助手select_year和朋友的解决方案:
<%=
select_year(
my_object.date_field.try(:year),
{
:prompt => "",
:start_year => Time.zone.now.year,
:end_year => Time.zone.now.year + 4,
:field_name => :"date_field(1i)",
:prefix => :my_object
},
:class => "form-control"
)
%>
这有点难看,因为它没有从周围form
获取任何信息,我们必须使用(1i)设置所选值,特殊 field_name 等。
所以我最终得到了一个帮手:
module DateSelectHelper
def date_select_year(object, field_name, opts = {}, html_opts = {})
merged_opts = {
:prompt => "",
:start_year => Time.zone.now.year,
:end_year => Time.zone.now.year + 4,
:field_name => :"#{field_name}(1i)",
:prefix => object.class.name.underscore
}.merge(opts)
select_year(object.send(field_name).try(:year), merged_opts, html_opts)
end
def date_select_month(object, field_name, opts = {}, html_opts = {})
merged_opts = {
:prompt => "",
:field_name => :"#{field_name}(2i)",
:prefix => object.class.name.underscore
}.merge(opts)
select_month(object.send(field_name).try(:month), merged_opts, html_opts)
end
def date_select_day(object, field_name, opts = {}, html_opts = {})
merged_opts = {
:prompt => "",
:field_name => :"#{field_name}(3i)",
:prefix => object.class.name.underscore
}.merge(opts)
select_day(object.send(field_name).try(:day), merged_opts, html_opts)
end
end
你可以像这样使用它:
<div class="col-sm-2">
<%= date_select_year(f.object, :date_field, { :start_year => Time.zone.now.year, :end_year => Time.zone.now.year + 4 }, { :class => "form-control" }) %>
</div>
<div class="col-sm-3">
<%= date_select_month(f.object, :date_field, {}, { :class => "form-control" }) %>
</div>
<div class="col-sm-2">
<%= date_select_day(f.object, :date_field, {}, { :class => "form-control" }) %>
</div>
我还在测试它..但它看起来很有效。