Версия для печати темы
Нажмите сюда для просмотра этой темы в оригинальном формате
Форум программистов > Ruby On Rails > Создание справочника при помощи рекурсии в Mongoid


Автор: 13ga1ka 29.1.2015, 09:22
Добрый день! У меня возникла проблема при создании справочника материалов, в котором должны быть категории и вложенные в них подкатегории и материалы соответственно. Имеется модель app/models/book/material/category.rb и контроллеp app/controllers/book/materials/categories_controller.rb со следующим кодом:

category.rb

Код

class Book::Material::Category
  include Mongoid::Document
  include Mongoid::Timestamps

  field :name, type: String

  attr_accessor :pid

  embeds_many :materials, inverse_of: :category
  belongs_to :user, inverse_of: :book_material_categories
  recursively_embeds_many

  validates :name, presence: true

  def self.find_in_tree(collection, id)
    collection.each do |category|
        return category if category.id.to_s == id.to_s
        return find_in_tree(category.child_categories, id) unless category.child_categories.empty?
    end
  end
end
 

categories_controller.rb

Код

class Book::Materials::CategoriesController < ApplicationController
  add_breadcrumb 'Категории материалов', :book_materials_index_path
  before_filter :find_category, only: [:edit, :destroy, :update]
  before_filter :set_breadcrumb_new, only: [:new, :create]
  before_filter :set_breadcrumb_edit, only: [:edit, :update]

  def index
    @categories = current_user.clinic.book_material_categories
  end

  def new
    @category = Book::Material::Category.new
    @category.pid = params[:category_id] if params[:category_id].present?
  end

  def create

    @category = Book::Material::Category.new(params_book_material_category)
    @category.user_id = current_user.id
    ap @category
    pid = params[:book_material_category][:pid]
    if pid.present?
      ap @parent
      @parent = Book::Material::Category.find_in_tree(current_user.clinic.book_material_categories, pid)
      if @parent.child_categories << @category
        redirect_to book_materials_index_path
      else
        render :new
      end
    else
      if @category.save
        redirect_to book_materials_index_path
      else
        render :new
      end
    end
  end

  def edit; end

  def update
    if @category.update_attributes(params_book_material_category)
      redirect_to book_materials_index_path
    else
      render :edit
    end
  end

  def destroy
    @category.destroy
    redirect_to book_materials_index_path
  end

  private

  def params_book_material_category
    params.require(:book_material_category).permit(:name, :pid)
  end

  def find_category
    @category = Book::Material::Category.find_in_tree(current_user.clinic.book_material_categories, params[:id])
  end

  def set_breadcrumb_new
    add_breadcrumb 'Добавление', new_book_materials_category_path
  end

  def set_breadcrumb_edit
    add_breadcrumb 'Редактирование', edit_book_materials_category_path(@category)
  end
end


Прошу помочь разобраться с методом find_in_tree в модели category.rb, я склоняюсь к тому, что он работает не правильно, так как он ищет только по первому уровню, а дальше возникает ошибка при вложении подкатегорий. Я новичок в Ruby on Rails, и поэтому любая ваша помощь будет ценной для меня. 

Заранее большое спасибо)) 

Powered by Invision Power Board (http://www.invisionboard.com)
© Invision Power Services (http://www.invisionpower.com)