我对 Ruby on Rails 非常陌生,正在开发一个目录应用程序。我已经设置了数据库并添加了一些条目。目前,在我的主页上,它正在显示数据库中的所有数据,但我如何才能仅显示一条记录。这是我的代码:
<% if notice %>
<p id="notice"><%= notice %></p>
<% end %>
<h1>Bann.com - slightly smaller than Amazon!</h1>
<% @products.each do |product| %>
<div class="entry">
<table border="1">
<tr>
<th>Header 1</th>
<th>Header 2</th>
</tr>
<tr>
<td><%= image_tag(product.image_url) %></td>
<td><%= image_tag(product.image_url) %></td>
</tr>
<tr>
<td><h3><%= product.title %></h3>
<div class="price_line">
<span class="price"><%= number_to_currency product.price, :unit=>'£' %></span>
</div>
</div></td>
<td>row 2, cell 2</td>
</tr>
</table>
<% end %>
最佳答案
现在,您正在 @products.each do |product|
循环中循环遍历 products 中的所有内容。如果您只想显示其中第一个,您可以:
<% if notice %>
<p id="notice"><%= notice %></p>
<% end %>
<h1>Bann.com - slightly smaller than Amazon!</h1>
<% product = @products.first %>
<div class="entry">
<table border="1">
<tr>
<th>Header 1</th>
<th>Header 2</th>
</tr>
<tr>
<td><%= image_tag(product.image_url) %></td>
<td><%= image_tag(product.image_url) %></td>
</tr>
<tr>
<td>
<h3><%= product.title %></h3>
<div class="price_line">
<span class="price"><%= number_to_currency product.price, :unit=>'£' %></span>
</div>
</td>
<td>row 2, cell 2</td>
</tr>
</table>
</div>
我还修复了你的 div。当您的起始 div 位于它之前时,您的表格中间就会有一个关闭的 div。
关于ruby-on-rails - 如何在 ruby on Rails 中显示数据库中的单个记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20637500/