首页 > 解决方案 > Rails 循环遍历数据库表并按名称拒绝一个对象

问题描述

我正在根据以下内容在数据库表中搜索对象id

def edit
  @attachments = Attachment.where(item_id: @item.id)
end

在视图内部,我试图拒绝这样的no-image.jpg图像:

<% @attachments.reject { |attachment| attachment.image.file.identifier == "no-image.jpg" }.each do |attachment| %>
    <%= image_tag(attachment.image.url(:mini))%>
    <%= link_to "Remove", remove_item_attachment_path(attachment), :data => {:confirm => 'Are you sure?'}, :method => :delete %>
<% end %>

现在即使no-image.jpg当我调试它时文件存在于循环中,它也会给出以下错误:

NoMethodError in Items#edit
undefined method `identifier' for #<CarrierWave::Storage::Fog::File:0x007fb193633520>

错误在这一行:

<% @attachments.reject { |attachment| attachment.image.file.identifier == "no-image.jpg" }.each do |attachment| %>

有什么想法可以解决这个问题吗?

标签: ruby-on-railsruby

解决方案


看到你也写attachment.image.url我假设image是图像存储在Attachment类中的字段,所以在这种情况下你应该写

attachment.image.identifier 

我觉得attachment.image_identifier也是可以的。


推荐阅读