有没有一种方法可以使用主动存储循环遍历许多附加的图像

发布于 2025-02-13 05:17:31 字数 780 浏览 0 评论 0原文

我已经安装了Active Storage,我想要一个 post 类或模型具有一个或多个图像,因此我创建了一个类似的关联:

class Post < ApplicationRecord
   has_many_attached :images
end

我可以创建一个帖子,并且我允许参数中的图像,我已经启用了多个上传,可以成功创建帖子,但是当我想像下面的视图上迭代图像时,我什么都没有得到;

<% @post.images.each do |image| %>
  <%= image_tag(image) %>
<%end%>

当我尝试仅显示一个图像而不像下面这样的循环时,我会收到一个错误,说无法将图像解析到URL中:未定义的方法 to_model'`。

<%= image_tag(@post.images) %>

到目前为止,这就是我尝试过的,当我只是在嵌入式红宝石中显示@post.images 时,我可以在下面获得一些信息,实际上图像就在那里。

有没有做错事?

I have installed active storage and I want a Post class or model to have one or many images so I created an association like below:

class Post < ApplicationRecord
   has_many_attached :images
end

I can create a post and I have allowed the images in the parameters and I have enabled multiple uploads and the post can be created successfully but when I want to iterate the images on the view like below I get nothing;

<% @post.images.each do |image| %>
  <%= image_tag(image) %>
<%end%>

When I try to just display one image without looping like below I get an error saying Can't resolve image into URL: undefined methodto_model'`.

<%= image_tag(@post.images) %>

So far that is what I have tried and when I just display the @post.images in an embedded ruby I can get some information like below that indeed the images are there.

Active storage details

Is there anything am doing wrong?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

铃予 2025-02-20 05:17:32

我以前通过这种方式实现了这一点。

class Post < ApplicationRecord
 has_many_attached :images
end

您的帖子的图像应包含在参数中:

def car_params
  params.require(:car).permit(:name, :description, :comments, images:[])
end

然后在视图中,我以这种方式循环浏览图像:

<% if @post.images.attached? %>
  <% @car.images.each do |image| %>
   <li>
    <button type="button" >
      <%= image_tag(url_for(image)) %>
    </button>
   </li>
  <% end %>
 <% end %>

如果您想在不循环的情况下选择一个图像,那么您可以通过索引选择。

<%= image_tag(@post.images[0]) %>

如果您寻求循环循环,请继续使用URL标签,因为它可以更好地工作。

I implemented this previously by doing it this way.

class Post < ApplicationRecord
 has_many_attached :images
end

The images for your post should included in the params as such:

def car_params
  params.require(:car).permit(:name, :description, :comments, images:[])
end

Then in the views, I looped through the images this way:

<% if @post.images.attached? %>
  <% @car.images.each do |image| %>
   <li>
    <button type="button" >
      <%= image_tag(url_for(image)) %>
    </button>
   </li>
  <% end %>
 <% end %>

If you want to select one image without looping, then you can select by the index.

<%= image_tag(@post.images[0]) %>

If you seek to loop through, go ahead with the url tag as that works better.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文