如何在表单中选择类别,然后显示要选择的category.sizes列表

时间:2015-12-01 11:45:17

标签: ruby-on-rails ruby-on-rails-3 ruby-on-rails-4

我有3种型号的产品,类别和尺寸。

在我的产品新视图中,我可以选择一个类别。

当我选择一个类别时,我希望类别大小显示在它下面作为勾选框列表。你怎么做到这一点?。示例:有人可能选择牛仔裤作为类别,然后下面将显示牛仔裤的所有尺寸作为勾选框

提前感谢您的帮助。

这是我的产品视图

<div class="container">
  <div class=“row”>
    <div class="col-md-6 col-md-offset-3">
      <div class="panel panel-primary">
        <div class="panel-body">
          <%= simple_form_for @product, html: { multipart: true } do |f| %>
            <%= f.input :image, label:"Choose Image"%>
            <%= f.collection_select :category_id, Category.order(:name), :id, :name, include_blank: true, :prompt => "Select One Category" %>
            <%= f.input :title, label:"Title"%>
            <%= f.input :price, label:"Price"%>
            <%= f.input :description,label:"Description" %>
            <%= f.input :tag_list,label:"Tags - Seperate tags using comma ','. 5 tags allowed per product" %>
            <%= f.button :submit, "Create new product", class: "btn-lg btn-success" %>
          <% end %>
        </div>
      </div>
    </div>
  </div>
</div>

产品型号

class Product < ActiveRecord::Base
  acts_as_taggable

    belongs_to :user
    belongs_to :category

  has_many :product_sizes

    validates :title, presence: true, length: { maximum: 30 }
    validates :description, presence: true, length: { maximum: 2000 }
    validates :category, :user_id, :price, presence: true

    has_attached_file :image, styles: { large: "600x600", medium: "250x250", thumb:"100x100#"}
    validates_attachment_content_type :image, content_type: /\Aimage\/.*\Z/
end

类别模型

class Category < ActiveRecord::Base
  has_ancestry

  has_many :products
  has_many :sizes

  validates :name, presence: true, length: { maximum: 20 }, uniqueness: true

  accepts_nested_attributes_for :sizes, allow_destroy: true
end

尺寸模型

class Size < ActiveRecord::Base
    validates :title, presence: true, length: { maximum: 15 }
    validates :title, uniqueness: true

  belongs_to :category
end

1 个答案:

答案 0 :(得分:0)

我看到至少2种可能的选择(取决于类别和性能的数量)。

1)你应该创建一个复选框并将它们包装在一个隐藏的div&amp;如果选择了特定类别,则显示它们。例如:

修改表格:

#load @categories in controller (@categories = Category.preload(:sizes).order(:name))
<%= f.collection_select :category_id, @categories, :id, :name, include_blank: true, :prompt => "Select One Category" %>
<% @categories.each do |category| %>
  <div class='sizes_container' id ='sizes_container_for_<%= category.id %>' style='display:none'>
   <% category.sizes.each do |size| %>
     <!-- place checkboxes here -->
   <% end %>
  </div>
<% end %>

添加Js(更改后的Js将显示正确的复选框)

$('#product_category_id').on('change', function(){
  $('.sizes_container input').hide();
  $('.sizes_container input').removeAttr('checked');
  $('#sizes_container_for_' + $(this).val()).show();
})

2)在选择更改时,您应该ajax call到服务器,获取尺寸&amp;为他们建立复选框