2013-03-11 98 views
0

我需要在頁面中鏈接圖像。我的代碼是:Rails:如何分配鏈接到圖像

<%= image_tag p.photos.first.avatar.url(:small) if p.photos.size > 0 %> 

如何使此鏈接?

試着這樣做:

<%= link_to (image_tag p.photos.first.avatar.url(:small) if p.photos.size > 0), product_path(p.id) %> 

但給人語法錯誤。

任何一個?

回答

2

變化的鏈路使用塊形式(爲了更好的可讀性)

<%= link_to product_path(p.id) do %> 
    <% if p.photos.any? %> 
    <%= image_tag(p.photos.first.avatar.url(:small)) %> 
    <% else %> 
    <div>Default text for the link if the image is not present</div> 
    <% end %> 
<% end %> 
+0

這真的很棒。我現在做軌道2年,但我不知道link_to可以處理塊^^ – davidb 2013-03-11 08:59:15

+0

是的,我們都學習新的東西每天:) – jvnill 2013-03-11 09:01:35

+0

哇!像魅力一樣工作。非常感謝。正在尋找解決方案,從很多天。 :-) – user1977201 2013-03-11 09:29:09

1
<%= link_to image_tag(p.photos.first.avatar.url(:small)).html_safe, product_path(p.id) if p.photos.size > 0%> 
+0

不工作..不顯示圖像。 – user1977201 2013-03-11 09:28:24