Adding Sub-categories in Rails4

大兔子大兔子 提交于 2019-12-08 09:39:25

问题


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

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.

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?

Thank you.


回答1:


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

And edit app/models/category.rb

class Category < ActiveRecord::Base

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

end

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

EDIT:

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

And the form for your categories:

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


来源:https://stackoverflow.com/questions/18237745/adding-sub-categories-in-rails4

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!