Wednesday, May 13, 2009

URL insertion validation in a Ruby on Rails form.

Hi !
I have been searching for a little bit how to make sure that when the user enters a URL in the URL field, the URL has a correct format.
I could have done it using JavaScript, but the idea was to use the controller instead.
So this is what I came up with.


class Comment < ActiveRecord::Base

belongs_to :post
validates_presence_of :nickname, :message => ": can not be blank."
validates_presence_of :content, :message => ": can not be blank."
validate :correct_url

protected
def correct_url
if website.length > 0 and !website.match(/^(http|https):\/\/[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(([0-9]{1,5})?\/.*)?$/ix)
errors.add(:website, ": Please enter a valid URL (http://www.mysite.com).")
end
end
end


The correct_url function checks if the lenght of the field is > 0, means that the user inserted something, and then check if it matches the regular expression. If it doesn't,then we add a error message to the list of errors.

Hope this helps.
Martin





Tuesday, May 12, 2009

Count returned result Ruby On Rails

In order to display the number of items of a type, use the count method.

I have two classes Type and Entities. An entity has a type. If I want to count how many entities have the same type I would do


(<%= Entity.count(:conditions =>{:Type_id => type.id})%>)
or


(<%= Entity.count(:conditions =>{:Type_id => type.1})%>)

Which would return something like

Number of entities (26)

Thursday, May 7, 2009

Render partial sort results Ruby on Rails

I've been following this excellent tutorial about how to create a blog using ruby on rails in 15 minutes, but when it came to how to sort the comments, I was a little bit disapointed.
Having comments sorted from the oldest to the most recent is not something that I was pleased with.
After searching on the web I didn't find much solutions, so I asked for help railforum.com and here is something that hopefully will help you.
If you just want to order your items by id DESC then do :
<%= render :partial => post.comments.reverse  %>
If you want to pass a parameter to order by then :


<%= render :partial => post.comments.sort_by { |c| c.title} %>
<%= render :partial => post.comments.sort_by { |c| c.created_at} %>

and you can even reverse them


<%= render :partial => post.comments.sort_by { |c| c.title}.reverse %>



Hope this help.
Martin