I’m having trouble using an application helper and understanding how I
should make it work throughout my application - so if you can help me
with this I’ll be overcoming a big hurdle in my learning.
Here’s the helper method;
[code=]# application_helper.rb
def user_photo
if @user.photo?
return @user.photo.public_filename(:thumb)
else
return ‘rails.png’
end
end[/code]
Pretty simple. I understand what it does, and it works just fine in my
show action in the user controller;
[code=]# user_controller.rb
def show
@user = User.find(params[:id])
end[/code]
[code=]# show.html.erb
<%= @user.login %>
Email: <%= @user.email %>
Joined: <%= @user.created_at.to_s(:long) %>
Posts: <%= @user.posts.count %>
However, I want this helper to work elsewhere in the app, such as a
_post partial, which obviously is called on the Post index and show
actions, etc. But because the user_photo method uses the @user instance
variable, I need to make it work when @user isn’t set in the current
controller, e.g. the posts index action (if I use the user_photo in the
_post partial on the post index action, I inevitably get a nil object
because @user.photo doesn’t exist);
[code=]def index
@posts = Post.list(params[:page])
respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => @posts }
end
end[/code]
I’m already pulling @posts on the post index (and there is a
‘post.user.photo’ in every ‘post’ in @posts); do I need to define the
@user instance variable in all the necessary controller actions, by
doing something like this;
[code=]def index
@posts = Post.list(params[:page])
@user = “post.user for every post in @posts” # something along those
lines…
respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => @posts }
format.rss { render :rss => @posts }
end
end[/code]
Or can I do this in a different way which doesn’t involve defining @user
in every controller action ?