Vince,
Perhaps you should have a look at how Ruby does objects, methods, and
variables? The Poignant Guide might be helpful:
http://poignantguide.net/ruby/
Anyhow, you don’t need this line if you’re using “user.id” to refer
to the user’s id:
user_id = user.id
Also, since you’re using session[:user] to store a user’s id, you
could get away with removing the first two lines and just doing this:
@product_pages, @products = paginate :products, :per_page =>
10, :conditions => [‘user_id = ?’, session[:user]]
But maybe it’s not a good idea to assume there’ll be a usable user id
in session[:user]. Plus, maybe you have a few actions in that
controller that refer to the same user. In that case, you could write
a private (or protected, maybe) function like this:
def find_user
@user = User.find(session[:user])
end
That sets the @user instance variable to the user that’s referred to
in the session, so you can use @user in other methods. You might say:
@product_pages, @products = paginate :products, :per_page =>
10, :conditions => [‘user_id = ?’, @user.id]
And so you don’t have to call find_user in every method, you could
use a filter:
before_filter :find_user
Or (and this is what I do sometimes) you could have a function called
“current_user” which returns the user with the id stored in session
[:user]:
def current_user
@current_user ||= User.find(session[:user])
end
This says (sort of) "if the @current_user instance variable isn’t set
already, set it to the user that the User model finds with the user
id in the session, and then return the value of @current_user. Then
you can say:
@product_pages, @products = paginate :products, :per_page =>
10, :conditions => [‘user_id = ?’, current_user.id]
Also, if you’re just starting to develop your application and you
don’t have a login system yet, (which is really easy to add later but
is pretty mechanical, so it’s a good idea to ignore it) you could
just tell current_user to return, for example:
User.find_by_name(“vince”)
And you’re always logged in! When you put your login system in, just
tell current_user to look at the session, or however else you might
keep track of users.
– Michael D.
http://www.mdaines.com