[英]How do I get the attributes of an object in ruby?
I'm new to Ruby and Rails. 我是Ruby和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:
因此,在ERB中,当您具有类似以下的标签时:
<% 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. 最好将SQL调用和大量逻辑保留在您的视图之外。 Leverage the controllers, models and helpers to do that.
利用控制器,模型和助手来做到这一点。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.