我试图在一个表中写一个if语句,以获得一个图像,如果一个图像不存在于数据库中。 我可以分别检索两个图像,但不能用if语句。 我在代码中做错了什么。
<h1>Won Auctions</h1>
<br>
<table class= "table table-hover" >
<thead>
<tr>
<th>Name</th>
<th>Price</th>
<th>End Date</th>
<th>Seller</th>
<th colspan="3"></th>
</tr>
</thead>
<tbody>
<% won.each do |a| %>
<tr>
<td><%=
if a.image.exists? %>
<% image_tag(a.image, width:100) %>
else
<% image_tag("No_image.jpg", width:100) %>
<% end %>
%><td>
<td><%= a.name %></td>
<td><%= number_to_currency(a.highest_bid) %></td>
<td><%= a.auction_end_time %></td>
<td><%= a.seller.email %></td>
</tr>
<% end %>
</tbody>
</table>
<br>
我在做什么?else
也需要放在ERB标签中。
此外,您需要将 <%=
和 <%
. 因为你想输出图像标签,所以使用了 <%=
随着 image_tag
. 但你没有输出 if
条件、用途 <%
随着 if
, else
和 end
.
<td>
<% if a.image.exists? %>
<%= image_tag(a.image, width:100) %>
<% else %>
<%= image_tag("No_image.jpg", width:100) %>
<% end %>
<td>
为了简化视图,我可以考虑在你的 a
模型(我想这是一个 Auction
),只需在视图中调用该帮助方法,而不是在视图中设置条件。
# in the model
FALLBACK_IMAGE_PATH = 'No_image.jpg'
def image_path_with_fallback
a.image.exists? ? a.image : FALLBACK_IMAGE_PATH
end
# in the view
<td><%= image_tag(a.image_path_with_fallback, width:100) %><td>