将一串衣服尺码 "xs,s,m,l,xl" 变成一些你可以 select

Turn A String Of Clothes Sizes "xs,s,m,l,xl" into some you can select

您好,我有一个项目模型和一个类别模型。创建 Shirt 类别时,您可以创建您希望 Shirt 类别具有的所有尺码。

目前尺码是字符串“XS、S、M、L、XL、XLL”

我要怎么做才能做到这一点 select?

例如,当您创建黄色衬衫项目时,您可能只有 XS 和 L 可用。

见下文

2.2.1 :002 > c = Category.last
  Category Load (0.3ms)  SELECT  "categories".* FROM "categories"  ORDER BY "categories"."id" DESC LIMIT 1
 => #<Category id: 14, name: "Shirt", ancestry: nil, created_at: "2015-09-01 10:09:32", updated_at: "2015-09-01 10:09:32", sizes: "XS, S, M, L, XL, XLL">
2.2.1 :003 > c
 => #<Category id: 14, name: "Shirt", ancestry: nil, created_at: "2015-09-01 10:09:32", updated_at: "2015-09-01 10:09:32", sizes: "XS, S, M, L, XL, XLL">
2.2.1 :004 > c.sizes
 => "XS, S, M, L, XL, XLL"

类别控制器

class CategoriesController < ApplicationController
  before_action :set_category,   only: [:show]
  before_action :admin_user,     only: [:destroy, :index, :edit]

  def index
    @categories = Category.all
  end

  def show
    @tags = Item.where(category_id: @category.id).tag_counts_on(:tags)
    if params[:tag]
      @items = Item.tagged_with(params[:tag])
    else
      @items = Item.where(category_id: @category.id).order("created_at DESC")
    end
  end

  def new
    @category = Category.new
  end

  def edit
  end

  def create
    @category = Category.new(category_params)

    respond_to do |format|
      if @category.save
        format.html { redirect_to @category, notice: 'Category was successfully created.' }
        format.json { render :show, status: :created, location: @category }
      else
        format.html { render :new }
        format.json { render json: @category.errors, status: :unprocessable_entity }
      end
    end
  end

  def update
    respond_to do |format|
      if @category.update(category_params)
        format.html { redirect_to @category, notice: 'Category was successfully updated.' }
        format.json { render :show, status: :ok, location: @category }
      else
        format.html { render :edit }
        format.json { render json: @category.errors, status: :unprocessable_entity }
      end
    end
  end

  def destroy
    @category.destroy
    respond_to do |format|
      format.html { redirect_to categories_url, notice: 'Category was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

  private

    def set_category
      @category = Category.find(params[:id])
    end

    def category_params
      params.require(:category).permit(:name, :sizes, :parent_id)
    end
    
    # Confirms an admin user.
    def admin_user
      redirect_to(root_url) unless current_user.try(:admin?)
    end
    
end

分类表

<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(@category) do |f| %>
          <div class="form-inputs">
          <%= f.input :name %>
          <%= f.input :sizes %>
          <%= f.collection_select :parent_id, Category.order(:name), :id, :name, include_blank: true %>
          </div>
          <div class="form-actions">
          <%= f.button :submit %>
          </div>
          <% end %>
        </div>
      </div>    
    </div>
  </div>
</div>

如果您需要项目视图

<h1>Create New item</h1>

<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 @item, html: { multipart: true } do |f| %>
            <%= f.input :image%>
            <%= f.collection_select :category_id, Category.order(:name), :id, :name, include_blank: true, :prompt => "Select One Category" %>
            <%= f.input :tag_list %>
            <%= f.input :title%>
            <%= f.input :price %>
            <%= f.input :description %>
            <%= f.button :submit, "Create new item", class: "btn btn-primary" %>
          <% end %>
        </div>
      </div>    
    </div>
  </div>
</div>

将大小转换为数组的迁移。

class AddSizesToCategories < ActiveRecord::Migration
  def change
    add_column :categories, :sizes, :string, array: true, default: []
  end
end

您可以为此使用枚举类型。在您的类别模型中,您可以定义所有可能的值:

enum sizes: [:xs, :s, :m, :l, :xl, :xll]

在数据库中,枚举类型存储为整数,因此您可以使用整数数组,所以基本上在您的迁移中,您只需将其更改为:

add_column :categories, :sizes, :integer, array: true, default: []

在您的表单中,您可以像这样从此枚举类型中获取值:

<%= f.input :sizes, collection: Category.sizes.keys, as: :check_boxes, input_html: { multiple: true } %>

在您的 categories_controller 中,您还需要像这样为 sizes 参数允许数组:

def category_params
  params.require(:category).permit(:name, :parent_id, sizes: [])
end

您应该为此创建一个 array/enumrator,并且可以在应用程序的任何位置访问它。所以在config/initializers下创建一个initialize.rb文件。

## config/initializers/initialize.rb

CATEGORIES = [["XS","XS"],["S","S"],["M","M"],["L","L"],["XL","XL"],["XLL","XLL"]]

在您的类别表单中更改: <%= f.input:尺寸 %>

<%= f.collection_check_boxes :sizes, CATEGORIES%>

当您提交表单并选择 XS, L, XLL 时,您将获得参数 params[:category][:sizes],例如 ["XS"、"L"、"XLL"]

将其更改为字符串格式并保存到数据库。你完成了