【问题标题】:image is not getting displayed in rails 6 views图像未在 rails 6 视图中显示
【发布时间】:2021-03-16 20:41:49
【问题描述】:

我的 rails 6 app 中有以下代码。使用主动存储将图像保存到数据库中

<%= form_for(@business, url: supplier_save_business_categories_path, :html => {method: :post } ) do |f| %>
  <%= f.collection_check_boxes(:category_ids, Category.all, :id, :name) do |b| %>
     <%= b.label class: "check_box" do%>
       <%#= image_tag(url_for(b.image)) if b.image.present? %> image is not getting displayed here.
       <%=b.check_box style: "display: none;"%> <%= b.text %>
     < %end%>
<% end %>

试图像这样显示类别图像。

<%#= image_tag(url_for(b.image)) if b.image.present? %> 

但图像未在此处显示。当类别名称从类别记录的数据库中显示时,我不知道为什么类别图像没有显示。

得到以下错误。

undefined method `image' for #<ActionView::Helpers::Tags::CollectionCheckBoxes::CheckBoxBuilder:0x00007fb6205a48c0>

【问题讨论】:

    标签: ruby-on-rails image checkbox collections rails-activestorage


    【解决方案1】:

    如果您查看officiel docs,您会发现collection_check_boxes 方法旨在为您提供一个带有值(通常是ID)和标签(通常是名称/文本)的复选框。由于您有记录的 id,您可以去查找记录并获取图像 url。像这样的:

    <%= form_for(@business, url: supplier_save_business_categories_path, :html => {method: :post } ) do |f| %>
      <%= f.collection_check_boxes(:category_ids, Category.all, :id, :name) do |b| %>
         <%= b.label class: "check_box" do%>
           <%= image_tag(url_for(category_image(b.id))) unless category_image(b.id).nil? %>
           <%=b.check_box style: "display: none;"%> <%= b.text %>
         < % end %>
       <% end %>
    <% end %>
    
    # CategoryHelper
    def category_image(category_id)
      category = Category.find(category_id)
      if category
        category.image
      else
        nil
      end
    end
    

    【讨论】:

      猜你喜欢
      • 2020-01-23
      • 2020-03-01
      • 2020-12-04
      • 1970-01-01
      • 2020-03-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多