Reputation: 71
I am very new to ruby on rails and am developing a catalogue application. I have set up my database and have added some entries. At the moment on my main page it is displaying all the data in my database but how do i go about just displaying one record for example. Here is my code:
<% 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 %>
Upvotes: 2
Views: 2355
Reputation: 10997
<% @products.each do |product| %>
is looping through all the data in your Product table.
if you open your terminal and type rake routes
you'll see a list of all the routes available. Probably you'll see a listing called 'product_path'. What you see is dependent upon what's in your config/routes.rb
file. You can read more about that here.
In your view, if you write <% link_to "THIS PRODUCT!", product_path(id: product.id) %>
inside of the each loop, you'll be directed to the show page for that specific product (so long as you have a view for it). From there you can start building your product show page. I would suggest you check this guide out and then look up the Michael Hartl tutorial. Both are very helpful :)
Upvotes: 0
Reputation: 1776
<% @products.each do |product| %>
is iterating through all the elements of the @products array, which is defined in your controller.
If you want to display just one product, you first have to decide which one, then retrieve it from the database in your controller, and use it to set a variable, eg @product
, which will be then available in your view.
Good luck.
Upvotes: 0
Reputation: 5182
Right now you're looping over everything in products in your @products.each do |product|
loop. If you wanted to display just the first of these, you could:
<% 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>
Also I fixed your divs. You've got a close div in the middle of your table when your start div is before it.
Upvotes: 2