Using Class Variables

Hello,
I haven't used class variables before (I'm new to RoR and OOP in
general...) and I think I need to use them for part of my program. I
have several different views for my controller "compare". For each view,
I need to grab the number of rows corresponding to several particular
SQL statements. I was thinking I could do something like this:

class CompareController < ApplicationController
@number_of_rows = Table.connection.select_all("
  SELECT
    COUNT(*) AS n
  FROM table")
@@numofrows = @number_of_rows.to_s.slice(1,3).to_i

def index
etc...

Then use @@numofrows in the view like so:

<%= link_to "entries (#{@@numofrows})", :controller => 'compare',
:action => 'index' %>

Obviously, this doesn't work. I am new to this type of programming and I
am trying to read up on all of this, but I am still very confused on how
to do this type of thing...

Any help is appreciated!

Thank you,
- Jeff Miller

Hi,

I’m not sure I know enough about what you want to do, but I suspect that neither class variables nor globals are a good solution. They almost never are.

If you want the count of rows in some table named “Table,” then you can obtain it with Table.count. You could store this in an instance variable, which will be available in your views. For example, in your controller,

def some_action
@row_count = Table.count
end

And in your view,

<%= link_to “entries (#{@row_count})”, :controller => ‘compare’, :action => ‘index’ %>

If you find yourself fetching the row count in several actions, you could investigate using a before_filter.

Good luck,
Craig

Hello,

I advice you to use your model when you run any operation for your
database.

Here is my code, i hope it can help you.