Rails复选框启用/禁用多个字段

时间:2012-03-19 09:57:07

标签: ruby-on-rails checkbox

我正在创建一个Rails 3.1应用程序,我希望在我的视图中添加一个复选框标记,我应该使用它来启用/禁用许多字段的编辑;我解释得更好:我有一个名为硬件的模型,我有两个名为'warranty_start'和'warranty_end'的硬件字段。这是相对于这些的代码:

<div class="group">
    <%= f.label :warranty_start, t("activerecord.attributes.warehouse.warrenty_start", :default => "Inizio garanzia"), :class => :label %>
    <%= f.date_select :warranty_start, :order => [:day, :month, :year], :class => 'date_select', :start_year => Time.now.year-3, :end_year => Time.now.year + 10 %>
  </div>
  <span class="description">Data di inizio Garanzia</span>
  <div class="group">
    <%= f.label :warranty_end, t("activerecord.attributes.warehouse.warrenty_end", :default => "Fine garanzia"), :class => :label %>
    <%= f.date_select :warranty_end, :order => [:day, :month, :year], :class => 'date_select',:start_year => Time.now.year-3, :end_year => Time.now.year + 10 %>
  </div>


    <span class="description">Data di fine Garanzia</span>

我想要一个复选框,如果启用,让用户选择warranty_start和warranty_end的日期。我可以这样做吗?

1 个答案:

答案 0 :(得分:2)

您必须使用JavaScript。也许使用jQuery。

HTML:

<div id="warranty">
    <!-- Here you put inputs with warranty start and end -->
</div>

JavaScript的:

$('#id_of_checkbox').click(function(){
    $('#warranty').css('display', ($(this).is(':checked') ? 'block' : 'none'));
});

在Rails中,您必须在模型中定义(更改:column_checkbox到列名:

class SomeModel < ActiveRecord::Base
    validates :warranty_start, :presence => true, :if => :warranty_want?
    validates :warranty_end, :presence => true, :if => :warranty_want?
    def warranty_want?
        warranty_checkbox == true
    end
    # rest of your model
end