I am trying to create my app using the Nested Set Gem here
I am trying to create a simple product menu for my app, so I would have something like this
+Category
–Category
—-Product
—-Product
–Category
—-Product
—-Product
My problem with the nested Set gem is that I don’t want the depth two be more then two category’s deep. The nested set gem by default allows something like this
+Category
–Category
—Category
—-Category
—–Product
But for our CSS Styling purposes, we don’t want to deal with that much depth, and the customer doesn’t need that much depth to it.
So i’m wondering if I even need the nested set in the first place, or will a standard has_many belongs_to work in this scenario? I am using Nested Set from the responses to this question here.
I am personally under the opinion that I may just use a standard has_many and belongs to, unless someone can inform me an advantage to using Nested Set in my case. If I do need it, how do I limit the customer from only selecting the correct depth to add a node to?
EDIT: Solved, Thanks.
My new problem is I am getting the error
undefined method `self_and_descendants’ for []:ActiveRecord::Relation
Extracted source (around line #9):
6: </p>
7: <p>
8: <%= f.label(:parent_id) %>
9: <%= f.select :parent_id, nested_set_options(Category.categories, @category) {|i, level| "#{'-' * level} #{i.name}" } %>
10: </p>
11: <p>
12: <% # f.label(:position) %>
views/categories/_form.html.erb
<%= form_for(@category) do |f| %>
<p>
<%= f.label(:name) %>
<%= f.text_field :name %>
</p>
<p>
<%= f.label(:parent_id) %>
<%= f.select :parent_id, nested_set_options(Category.categories, @category) {|i, level| "#{'-' * level} #{i.name}" } %>
</p>
<p>
<% # f.label(:position) %>
<% # f.select :position, 1..category_count %>
</p>
<p>
<%= f.submit("Submit") %>
</p>
<% end %>
models/category.rb
class Category < ActiveRecord::Base
acts_as_nested_set
acts_as_list :scope => :parent_id
has_many :products
scope :position, order("position asc")
scope :categories, where("parent_id IS NULL")
scope :subcategories, where("parent_id IS NOT NULL")
end
routes.rb (Shortened for space)
Locksmithing::Application.routes.draw do
resources :categories do
collection { post :sort }
resources :children, :controller => :categories, :only => [:index, :new, :create, :new_subcategory]
end
end
You could definitely continue using nested_set in this kind of context.
I have a hierarchical setup in the app I’m currently working on and while I allow infinite nesting, I only want the nav to show top 2 levels.
I have a named scope to let me limit what I’m looking at:
Such that (using Category from your example) you could use
You can pass that scope into any of nested_set’s scopes – or indeed the View Helper you’re probably aiming to use for limiting how many levels it can go.
To genuinely limit it, I’d also just place a validation constraint… before_save, checking that the depth is less than your max depth. Make sense?