I'm new to Ruby and Rails. I've been trying to get a view of all users to work and am not sure what I'm doing wrong.
I have a view with:
<% provide(:title, "View all Users") %>
<h1>Users#viewall</h1>
<p>Find me in app/views/users/viewall.html.erb</p>
<%
@users = User.all
@users.each do |user|
user.name
end
%>
The output of this is a list of objects in the database, with all the object's data. When I want to target (for example) just the name, it doesn't work.
[#<User id: 1, name: "user name", email: "mail@mail.com", created_at: "2016-08-03 15:40:41", updated_at: "2016-08-03 15:40:41", password_digest: "$2a$10$KmWWK86H/dj.HAp9zcHOUOCbph1rawIer41kyH4dIrV...">]
What am I missing here? I'm not even really sure what to google as I don't know what the loop is spitting out.
You are not displaying the data to the user.
In your controller method, is where you should add
@users = User.all
And in your view
<% @users.each do |user| %>
<h1><%= user.name %></h1>
<% end %>
You need to output the information. So in ERB when you have a tag like:
<% i = 4 %>
That executes code. When you have:
<%= "hi" %>
That outputs the return value. So what you actually want is this:
<% User.all.each do |user| %>
<%= user.name %>
<% end %>
What you should do with the users though, is setup an instance variable in your controller:
def viewall
@users = User.all
end
Then use it in your view:
<% @users.each do |user| %>
<%= user.name %>
<% end %>
Just better to keep SQL calls and a lot of logic out of your views. Leverage the controllers, models and helpers to do that.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.