欢迎来到cool的博客
7

Music box

Click to Start

点击头像播放音乐
新博客链接

如何使用 rails_gem : cocoon, 一级分类-新增二级分类

效果实例:

1.添加gem: (Inside your Gemfile add the following:)

gem "cocoon"

2.application.js:

//= require cocoon

3.新增一级分类的增删改查和二级分类的model:

Suppose you have a GoodsFirstCategory model:

rails g scaffold GoodsFirstCategory name:string 

新增二级分类的model和表:

rails g model RestaurantGoodsSecondCategory name:string goods_first_category_id:integer

4.添加model之间的关系:

class GoodsFirstCategory < ActiveRecord::Base
  has_many :restaurant_goods_second_categories, :before_add => :set_second_category

  accepts_nested_attributes_for :restaurant_goods_second_categories, allow_destroy: true

  has_many :goods

  def set_second_category(restaurant_goods_second_category)
    restaurant_goods_second_category.goods_first_category ||= self
  end
end

class RestaurantGoodsSecondCategory < ActiveRecord::Base
  belongs_to :goods_first_category

  has_many :goods
end

5.在   views/goods_first_categories/_form中添加代码:

  <div id="second_category" style="display: none">
    <div class="form-action">
      <%= link_to_add_association '新增二级分类', f, :restaurant_goods_second_categories, class: 'btn btn-success',
                                  'data-association-insertion-node' => '.restaurant_goods_second_categories',
                                  'data-association-insertion-method' => 'append' %>
    </div>

    <div class="restaurant_goods_second_categories">
      <%= f.fields_for :restaurant_goods_second_categories do |gsc| %>
          <%= render 'restaurant_goods_second_category_fields', f: gsc %>
      <% end %>
    </div>
  </div>

6.在 app/views/goods_first_categories/_restaurant_goods_second_category_fields.html.erb 添加:

<div class="detail-tr form-action">
    <%= f.text_field :name, :class => 'form-control', placeholder: '例如: 猪肉' %>
    <%= link_to_remove_association('删除', f,
                                   { wrapper_class: 'detail-tr' })%>
                                 <%= f.hidden_field :id %>
</div>

现在应该能增加二级分类了。

具体请参考:http://github.com/nathanvda/cocoon

返回列表