将一串衣服尺码“xs,s,m,l,xl”变成你可以选择的一些

时间:2015-09-01 10:27:15

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

你好,我有一个项目模型和一个类别模型。创建衬衫类别时,您可以创建衬衫类别所需的所有尺寸。

目前尺寸为字符串“XS,S,M,L,XL,XLL”

如何使其成为可以选择的内容?

例如,当您创建黄色衬衫项目时,您可能只有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

2 个答案:

答案 0 :(得分:1)

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

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中,您还需要允许size参数的数组,如下所示:

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

答案 1 :(得分:1)

您应该为此创建一个数组/枚举器,这可以在app中的任何位置访问。因此,请在initialize.rb下创建一个config/initializers文件。

## config/initializers/initialize.rb

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

在您的类别中更改表单:     &lt;%= f.input:sizes%&gt;

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

当提交表单并选择XS, L, XLL时,您将获得[{XS“,”L“,”XLL“]等参数params[:category][:sizes]

以字符串格式更改并保存到db。你完成了