Created
May 12, 2015 15:46
-
-
Save reiro/ed6d56a69d22d13834bd to your computer and use it in GitHub Desktop.
Создание Категорий и подкатегорий
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| rails g model category name:string parent:references | |
| class Category < ActiveRecord::Base | |
| has_many :subcategories, :class_name => "Category", :foreign_key => "parent_id", :dependent => :destroy | |
| belongs_to :parent_category, :class_name => "Category" | |
| end | |
| def index | |
| @category = nil | |
| @categories = Category.find(:all, :conditions => {:parent_id => nil } ) | |
| end | |
| # Show subcategory | |
| def show | |
| # Find the category belonging to the given id | |
| @category = Category.find(params[:id]) | |
| # Grab all sub-categories | |
| @categories = @category.subcategories | |
| # We want to reuse the index renderer: | |
| render :action => :index | |
| end | |
| def new | |
| @category = Category.new | |
| @category.parent = Category.find(params[:id]) unless params[:id].nil? | |
| end | |
| <h1><%= @category.nil? ? 'Main categories' : category.text %></h1> | |
| <table> | |
| <% @categories.each do |category| %> | |
| <tr> | |
| <td><%= link_to category.text, category_path(category) %></td> | |
| <td><%= link_to 'Edit', edit_category_path(category) unless category.parent.nil? %></td> | |
| <td><%= link_to 'Destroy', category_path(category), :confirm => 'Are you sure?', :method => :delete unless category.parent.nil? %></td> | |
| </tr> | |
| <% end %> | |
| </table> | |
| <p> | |
| <%= link_to 'Back', @category.parent.nil? ? categories_path : category_path(@category.parent) unless @category.nil? %> | |
| <%= link_to 'New (sub-category', new_category_path(@category) unless @category.nil? %> | |
| </p> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment