and then when i go to /users/list_friends the following code displays
fine
<h1>Your Friends Are</h1>
<% if flash[:notice] -%>
<div id="notice"><%= flash[:notice] %></div>
<% end -%>
<ul>
<% for user in @my_friends %>
<li>
<%= h(user.name) %>
</li>
<% end %>
</ul>
Yet when i add the code from list friends to the index page it all falls
over. I think i am missing some basic understanding of what is going on
here. The code for the list friends is.
def list_friends
if session[:user_id]
myuser = User.find(session[:user_id])
@my_friends = myuser.friends
else
flash[:notice] = "Please Login"
end
It looks like the problem you might be having is that you create an
object, @my_friends, in your action list_friends. If you want to call
this object on your index page, you would need to recreate it in the
index action of your controller.
You'll need to create @my_friends in the index action.
You might want to consider creating a current_user object across your
application. Check out the acts_as_authenticated plugin (http://
technoweenie.stikipad.com/plugins/show/Acts+as+Authenticated), it has
pretty much everything you'll need.
Using Acts as Authenticated, you can set a before_filter on specific
actions in your controller that checks if a user is logged in, and if
not, it redirects them to a login page. That way you can take the
logic for logging in out of your index page.
Then, you can simplify your actions to be something like
You can define it in your application controller, in /app/controllers/
application.rb, via a method like
def current_user
@current_user ||= (session[:user] &&
User.find_by_id(session[:user])) || :false
end
Acts as Authenticated will set up current_user for you, and it's
really easy to implement, there's a generate script that adds a file
to your /lib folder. Even if you don't want to use it, it will give
you a good idea of rails best practices for dealing with
authentication.
You're right, Rails books sometimes seem out-of-date because the
framework evolves pretty rapidly, but many of the same practices used
in the 1.2 book are still in use today, in addition to new practices
like greater emphasis on RESTful apps, sexy migrations, etc.