无论如何,Rails都将if语句添加到循环中

时间:2011-07-27 16:23:08

标签: ruby-on-rails ruby-on-rails-3

在我的rails应用程序中,我有一组显示的附件,主图像是其中之一。但是,除了主附件之外,我想遍历所有这些内容。我现在的观看代码是:

   <% if @asset.attachments.size > 0 %>
    <table>
        <tr>
    <% @asset.attachments.each_with_index do |attachment, i| %>
    <% if i%5 == 0 %>
        </tr><tr>
        <%end%>
    <td style="width: 150px;" valign="bottom" align="center">
    <%= image_tag(attachment.attachment.url(:thumb)) if attachment.is_image? %>
    <%= image_tag("/images/Excel.png") if attachment.is_excel? %>
    <%= image_tag("/images/Word.png") if attachment.is_word?%>
    <br />
    <%= link_to attachment.name.to_s,attachment.attachment.to_s %>
    </td>  
    <%end%>
    </tr>
    </table>
    <%end%>

但是,我想在这行代码中添加if!main_image之类的内容:

<% @asset.attachments.each_with_index do |attachment, i| %>

我不知道这是否可行。

3 个答案:

答案 0 :(得分:2)

<% @asset.attachments.each_with_index do |attachment, i| %>
  <% next if attachment.main_image %>

答案 1 :(得分:2)

这个答案将继续回答this question

为您的模型添加另一种方法,该方法会返回非主图像的附件。

scope :not_main_image, where(:main_image => false)

另外,您可能希望将所有这些逻辑移动到辅助方法中:

<%= image_tag(attachment.attachment.url(:thumb)) if attachment.is_image? %>
<%= image_tag("/images/Excel.png") if attachment.is_excel? %>
<%= image_tag("/images/Word.png") if attachment.is_word?%>
<br />
<%= link_to attachment.name.to_s,attachment.attachment.to_s>

假设您创建了一个辅助方法,如:

def link_to_attachment attachment
  html = ""
  html += image_tag(attachment.attachment.url(:thumb)) if attachment.is_image?
  html += image_tag("/images/Excel.png") if attachment.is_excel?
  html += image_tag("/images/Word.png") if attachment.is_word?
  html += "<br />"
  html += link_to(attachment.name.to_s, attachment.attachment.to_s)
  html.html_safe
end

然后在您查看中,您可以将其替换为:

<td style="width: 150px;" valign="bottom" align="center">
  <%= link_to_attachment attachment %>
</td>

答案 2 :(得分:0)

这取决于您如何定义主要附件

<% @asset.attachments.each_index do |attachment, i| %>
  <% unless attachment.main? %>
    ...
  <% end %>
<% end %>

OR

<% @asset.attachments.each_index do |attachment, i| %>
  <% if attachment.main? %>
    <% next %>
  <% else %>
    ...
  <% end %>
<% end %>

或将其放入您的控制器

@attachments = @asset.attachments.where(:main => false)

之后,迭代@attachments而不是@asset.attachments