我目前正在尝试学习 RoR,通常我在 Node.js 中开发,所以我所说的基于从数据库驱动的内容呈现页面的意思是:
如果我有一个标题、一个正文,也许还有一个日期,我该如何遍历一个表格,并为每个表格加载内容到页面上?在 Node.js(Jade 模板语言)中,它类似于:
for item in array
h2= item.title
p= item.date
p= item.body
希望我说清楚了,谢谢!
(它不一定是一个数组,它只是碰巧在 Node 中,不管最有效的方法是什么)
我目前正在尝试学习 RoR,通常我在 Node.js 中开发,所以我所说的基于从数据库驱动的内容呈现页面的意思是:
如果我有一个标题、一个正文,也许还有一个日期,我该如何遍历一个表格,并为每个表格加载内容到页面上?在 Node.js(Jade 模板语言)中,它类似于:
for item in array
h2= item.title
p= item.date
p= item.body
希望我说清楚了,谢谢!
(它不一定是一个数组,它只是碰巧在 Node 中,不管最有效的方法是什么)
您只是想遍历一个对象并显示数据吗?希望我没有误解你,但你可以访问这样的数据,例如:
array = YourActiveRecordObject.all
array.each do |item|
item.title
item.date
item.body
end
您可以在 haml 视图中使用它。
- array.each do |item|
%h2= item.title
%p= item.date
%p= item.body
Rails uses a Model-View-Controller organizational structure MVC. What you are looking for goes in the View for the particular resource. For example, if you scaffolded a resource called Item, you could go to app/views/items/index.html.erb and find this:
<% @items.each do |i| %>
<h2><%= i.title %></h2>
<p><%= i.date %></p>
<p><%= i.body %></p>
<% end %>
By default, Rails uses the ERB templating engine, but there are others available.
In controller you would define a variable @items for the array returned by the query to your model as:
@items = itemModel.all
#or whatever the query you need for those items are
And then in the view you would loop through them. With haml it would be:
- @items.each do |item|
%h2
= item.title
%p
= item.date
%p
= item.body