Topic: newb: counting rows

Hey all,

I'm entirely new to Ruby and Rails.  I'm not looking for code, but instead, I'm looking for guidelines to follow on how I should go about doing something. 

I have my database with the table, posts.  I'm trying to count how many "posts" are in the table where status="public"

So, how do I go about doing such a thing?  I have a PHP background, so my mentality is still such. 

I imagine I must define something in my model, call it in my controller, then output it in my view.  But, I'm completely lost.  I've tried searching, but the results just leave me even more confused.

Re: newb: counting rows

I'm assuming you have a Post model setup? You can do this in the controller if you want all the posts with that status:

def list # or whatever the action will be called
  @posts = Post.find(:all, :conditions => "status='public'")
end

Then whenever you want the count, you can do "@posts.size" in the view or controller.

However, if all you want is the count, and not the posts themselves, this is not very efficient. The "find" method grabs the post data from the database, makes little Ruby objects out of them and sticks them into an array. A lot of work for one number. smile

Here's the line you are looking for if you just want the count:

# in controller
@post_count = Post.count(:conditions => "status = 'public'")

Now you can display @post_count in the view.

Railscasts - Free Ruby on Rails Screencasts