Skip to content

Instantly share code, notes, and snippets.

@zporter
Created November 22, 2010 20:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zporter/710649 to your computer and use it in GitHub Desktop.
Save zporter/710649 to your computer and use it in GitHub Desktop.
options_for_select method to accommodate sub-categories
class Category < ActiveRecord::Base
has_many :categories, :order => 'order_by asc'
belongs_to :category
scope :order, order("order_by asc")
scope :main, where(:category_id => nil)
def options_for_select( selected = nil )
selected_attribute = ' selected="selected"' if self == selected
options_output = "<option value='#{self.id}'#{selected_attribute}>#{self.title}</option>"
self.categories.each do |category|
options_output += category.options_for_select( selected )
end
options_output.html_safe
end
end
<select>
<% Category.main.order.each do |category| %>
<%= category.options_for_select Category.find(2) %>
<% end %>
</select>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment