i’m trying to create a list of the items from my database. the problem is that i cant acces in my view/user/index.html.erb the variable(array) from my users_controller methods. I have been reading tuts and books but the way they tell me to crushes somewhere on the way. Any hint/help is appreciated, Thank you.
Controller:
class UsersController < ApplicationController
def index
render('list')
end
def list
@users = User.all
end
def show
@user = User.find(params[:id])
end
def new
@user = user.new
end
def create
@user = User.new(params[:user])
if @user.save
flash[:notice] = "User succesfully created!"
redirect_to(:action => 'list')
else
flash[:notice] = "User couldn't be created!"
render('new')
end
end
end
list.html.erb
<table>
<tr>
<td>
<th>Name
</td>
<td>
<th>Password
</td>
<td>
<th>Log status
</td>
<td>
<th>Warning
</td>
<td>
<th>Banned
</td>
</tr>
<% @users.each do |u| %>
<tr>
<td><%= u.name %></td>
<td><%= u.password %></td>
<td><%= u.log_status %></td>
<td><%= u.warning %></td>
<td><%= u.banned %></td>
</tr>
<%end%>
</table>
Error:
NoMethodError in Users#index
Showing /home/bogdan/ex/lynda/hW/app/views/users/list.html.erb where line #20 raised:
undefined method `each' for nil:NilClass
Extracted source (around line #20):
17: </td>
18: </tr>
19:
20: <% @users.each do |u|%>
21:
22: <tr>
23: <td><%= u.name %></td>
Because you are rendering a view without having the variables used in it:
Quick solution:
add this in your index action and then hit reload:
Detailed answer:
These two methods are action(execution cursor) go to another place ,whether it is view or action.It means transfer control to one place to another place. Those are example for dry principle but different uses.
“RENDER:”
Render has something to do with just rendering that part of the view without actually running the method again.It means if we use render method it go to corresponding view so it did not go to server with any request so it is fast.But it use data in that method means where it render from.
render also using for text,layout,file,template .
“REDIRECT:”
Redirect actually takes you to the page and does stuff from scratch. When we call redirect_to method it goes to that particular method
, it means this request go to server and then go to method and execute it
Ex:Example
Explanation:
The above example if name update go to list_users method else go back to edit view.In this if updated user name then go to list users and display list of users and their values ,if not back to edit if not update data cause of any validation or any thing back to view