Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

About this user

http://ifakedit.com

« Newer Snippets
Older Snippets »
Showing 1-2 of 2 total  RSS 

Custom validation with rails: words with more than 26 characters

This goes in whatever model you're validating. "Subject" can be any of the symbols in your model and doesn't need the : in front of it.
def validate
	if subject.split.any?{|w| w.length > 26}
		errors.add(:subject, "cannot have words more than 26 consecutive characters")
	end
end

Acts As Tree Category Display

You should have a categories table with a parent_id field. Root categories should have the parent_id of 0.

I modified this post:
http://www.bigbold.com/snippets/posts/show/296

because the first one worked if you did stuff in your view to make the root categories come up, but I agree with the commenter that things should be contained to the helper - however I've managed to break the DRY rule in doing so. If anyone has any suggestions for a better way around this I'd love to hear it, so please comment. So anyway.. this should list your root categories ONLY and NOT your other sub-cats as well so that you have a very pretty little tree.

Slap this in your view:

<%= display_categories(@categories) %>


And put this in a helper file. You'll need it in the application helper most likely since you'll want to call it from multiple views.

      def display_categories(categories)
	    	   ret = "<ul>"
	   for category in categories
		   if category.parent_id == 0
			ret += "<li>"
			ret += link_to category.name
			ret += find_all_subcategories(category)
			ret += "</li>"
		   end
		   
	   end
	   ret += "</ul>"
    end
    
   def find_all_subcategories(category)
    if category.children.size > 0
      ret = '<ul>'
      category.children.each { |subcat| 
        if subcat.children.size > 0
          ret += '<li>'
          ret += link_to h(subcat.name), :action => 'edit', :id => subcat
          ret += find_all_subcategories(subcat)
          ret += '</li>'
        else
          ret += '<li>'
          ret += link_to h(subcat.name), :action => 'edit', :id => subcat 
          ret += '</li>'
        end
        }
      ret += '</ul>'
    end
  end
« Newer Snippets
Older Snippets »
Showing 1-2 of 2 total  RSS