views:

58

answers:

2

Here's my index action in the books controller: http://pastebin.com/XdtGRQKV

Here's the view for the action i just mentioned: http://pastebin.com/nQFy400m

Here's the result without being logged in: http://i.imgur.com/rQoiw.jpg

Here's the result when i'm logged in with the user 'admin': http://i.imgur.com/E1CUr.jpg

So the problem is that, in the view, before line 25 the 'user' variable seems to be empty ( or not loaded), and after line 25 the variable 'user' has the expected values.

I have tried initializing a variable in the index method of the books controller but get exactly the same results.

Thanks in advance!

BTW had to make the links text because of stackoverflow limit.

+2  A: 

You didn't output user.username. It should be <%= user.username %>, not <% user.username %>

Voyta
+3  A: 

This:

user = User.find_by_id(session[:user_id])

should be in controller, not in view (MVC!) like this:

@user = User.find_by_id(session[:user_id])

Then in your view, as @Voyta answered, use <%= @user.username %>. Code inside <% %> is evaluated, but not rendered, so if you want to put result in your html, you need to add =.

And all yours if user and if user.admin == 1 would look much better this way:

<% if user %>
  <td><%= link_to 'Show', book %></td>
  <% if user.admin == 1 %>
    <td><%= link_to 'Edit', edit_book_path(book) %></td>
    <td><%= link_to 'Delete', book, :confirm => 'Are you sure?', :method => :delete %></td>
  <% end
 end
%>

If you use if in single line like here:

<%
 if user
  if user.admin == 1
%>
<%= link_to 'New book', new_book_path %>
<%
  end
end
%>

You can write the same like this:

<%= link_to 'New book', new_book_path if user && user.admin == 1 %>
klew