【发布时间】:2021-05-04 19:59:39
【问题描述】:
我确定这应该很简单,但我忽略了一些愚蠢的事情。
导轨 6.1.1 红宝石 3.0.0
我正在使用活动存储将多张“照片”附加到我的文章模型。
在文章“show.html.erb”中,我想将照片放置在文章中的多个不同位置,而不是在同一位置连续循环。
show.html.erb
<% @first2photos.each do |article| %>
<%= image_tag(article.photos) %>
<% end %>
articles.controller.erb
def show
@first2photos = Article.order("created_at DESC").first(2)
end
这会产生以下错误:
Can't resolve image into URL: undefined method `to_model' for #<ActiveStorage::Attached::Many:0x00007fdbbfa852a8 @name="photos", @record=#<Article id: 1, title: "This is the first post", snippet: "Hopefully this will also attach a couple of photos", body: "Nullam ac odio eget mauris accumsan malesuada. Nul...", created_at: "2021-01-30 20:50:31.766713000 +0000", updated_at: "2021-01-30 21:04:09.424224000 +0000">> Did you mean? to_yaml
如果我在“照片”上循环播放:
<% @first2photos.each do |photos| %>
<%= image_tag(@article.photos) %>
<% end %>
我仍然收到以下错误:
Can't resolve image into URL: undefined method `to_model'...
将其更改为:
<% @first2photos.each do |photos| %>
<%= image_tag(photos) %>
<% end %>
页面现在加载,但显示一个损坏的图像图标,没有错误。检查终端中的登录,我不确定我是否可以看到它试图访问照片的位置。
Started GET "/articles/1" for ::1 at 2021-01-31 20:56:58 +0000
Processing by ArticlesController#show as HTML
Parameters: {"id"=>"1"}
Article Load (2.9ms) SELECT "articles".* FROM "articles" WHERE "articles"."id" = $1 LIMIT $2 [["id", 1], ["LIMIT", 1]]
↳ app/controllers/articles_controller.rb:64:in `set_article'
Article Load (1.4ms) SELECT "articles".* FROM "articles" ORDER BY created_at DESC LIMIT $1 [["LIMIT", 2]]
↳ app/controllers/articles_controller.rb:11:in `show'
Rendering layout layouts/application.html.erb
Rendering articles/show.html.erb within layouts/application
Rendered articles/show.html.erb within layouts/application (Duration: 0.4ms | Allocations: 155)
[Webpacker] Everything's up-to-date. Nothing to do
Rendered layout layouts/application.html.erb (Duration: 8.6ms | Allocations: 4208)
Completed 200 OK in 20ms (Views: 9.3ms | ActiveRecord: 4.4ms | Allocations: 6022)
【问题讨论】:
-
您的关联中有多张照片,您必须遍历这些照片,然后为每张照片使用
image_tag(不是所有照片都使用image_tag) -
谢谢,不是'' 在多个图像上循环?
-
这是对文章的循环(你有
each do |article|),你需要在第一个循环内有一个article.photos.each do |photo| -
谢谢,@arieljuod。仍然没有得到这个。更新了 OP 的更多细节。
-
我添加了一个答案以使其更清晰
标签: ruby-on-rails rails-activestorage