【问题标题】:Adding Sub-categories in Rails4在 Rails4 中添加子类别
【发布时间】:2013-08-14 16:54:22
【问题描述】:

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

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

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

很多人建议我使用 gem,但由于我对 Rails 还很陌生,我宁愿自己学习如何做到这一点,从头到尾学习。

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

谁能解释我如何开始(迁移等)以及如何设置?

谢谢。

【问题讨论】:

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


    【解决方案1】:

    你必须用rails g model category生成一个新模型,然后编辑db/migrate中的文件生成并写下这个

    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 才能在您的数据库中创建表。

    编辑:

    在 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 %>
    

    【讨论】:

    • 如果我不生成脚手架,如何添加、编辑或销毁子类别?
    • 这取决于您想要的UX,您基本上可以为模型类别创建一个CRUD,并在每个类别创建和版本页面中设置父类别。
    • 哦哦哦 :( 我根本不明白。你能用如何为子类别生成脚手架来编辑你的答案吗?谢谢
    猜你喜欢
    • 2016-07-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-08
    • 2019-12-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多