在Rails4中添加子类别

在Rails4中添加子类别

本文介绍了在Rails4中添加子类别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有很多主要类别,想添加到每个子类别中.->

I have a lot of Main Categories and want to add to each sub categories.->

主要类别
-子类别
-子类别
-子类别

Main Category
-Sub Category
-Sub Category
-Sub Category

主要类别
-子类别
-子类别
-子类别

Main Category
-Sub Category
-Sub Category
-Sub Category

很多人建议我使用宝石,但是由于我对Rails还是很陌生,所以我宁愿自己学习如何做到这一点,也要学会所有方法.

A lot of people recommend me to use a gem, but as i am fairly new to Rails i rather learn how to do this on my own, to learn all they way through.

我应该以Scaffold还是简单地以Model开头?

Should i start with a Scaffold or simply a Model ?

有人可以向我解释如何开始(迁移等)以及如何进行设置吗?

Could someone explain me how to start (migrations etc.) and how to set it up?

谢谢.

推荐答案

您必须使用rails g model category生成新模型,然后编辑在db/migrate中生成的文件并将其编写

You have to generate a new model with rails g model category, then edit the file generate in db/migrate and write this

class CreateCategories < ActiveRecord::Migration
    def change
        create_table :categories do |t|
            t.belongs_to :category
            t.string :name, :null => false
            t.timestamps
        end
    end
end

并编辑app/models/category.rb

class Category < ActiveRecord::Base

    belongs_to :category
    has_many :children, :dependent => :destroy, :class_name => 'Category'

end

并且您必须执行rake db:migrate才能在数据库中创建表.

And you have to execute rake db:migrate for create the table in your database.

在app/controllers/categories_controller.rb

In app/controllers/categories_controller.rb

class CategoriesController < ApplicationController

    def index
        @categories = Category.all
    end

    def new
        @category = Category.new
    end

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

    def create
        @category = Category.new(params[:category].permit!)
        if @category.save
            redirect_to categories_url
        else
            render :new
        end
    end

    def update
        @category = Category.find(params[:id])
        if @category.update_attributes(params[:category].permit!)
            redirect_to categories_url
        else
            render :edit
        end
    end

    def destroy
        Category.destroy(params[:id])
        redirect_to categories_url
    end

end

以及您类别的表格:

<%= form_for @category do |f| %>

    <%= f.text_field :name %>
    <%= f.select :category_id, options_from_collection_for_select(Category.all, :id, :name, @category.category_id), :include_blank => true %>

    <%= f.submit %>

<% end %>

这篇关于在Rails4中添加子类别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-20 18:21