A Quickie
Posted about 1 year ago
No! Not that kind of quickie!!!
I should already be asleep but I feel like talking code. So lately I was blown away that the ActiveRecord contained a count method but ActionSupport did not. For instance to find the number of comments for each blog I ended up doing this in my controller:
@comment_count = Comment.count(:conditions => "blog_id = #{params[:id]}")
So in my blogs controller I have a class defined show that looks like this:
def show
@blog = Blog.find(params[:id])
@comment = Comment.new
@ip = request.remote_ip
respond_to do |format|
format.html
format.xml { render :xml => @blog }
end
end
All I really need to do in my view for show is:
<%= @blog.comments.count %>
Since blog.comments actually performs an ActiveRecord find it is of that class, and therefore has the count method available.
If you are not operating on an ActiveRecord class, then what you can do instead is use the size method. For example:
@posts = [1, 2, 3, 5, 10] => [1, 2, 3, 5, 10] @posts.size => 5
I really need to go to bed but I’m going to write tomorrow about some other fun things I’ve learned about Rails in the past couple days. Such as the lightbox plugin and more.
Sean



