ruby-on-rails - RoR: Displaying active storage images within an 'each' iteration?
问题描述
I'm trying to show user profile pics in a loop of tweets.
My models
user.rb
has_many :tweets
tweet.rb
belongs_to :user, optional: true
My view
<% @tweets.reverse.each do |tweet| %>
<strong><%= link_to tweet.user.email, thisuser_path(tweet.user_id) %></strong>
<br>
<%= tweets_index_avatar(@image_tweet) %>
....
<% end %>
My helper
def tweets_index_avatar(image_tweet)
if user.avatar.attached?
image_tag user.avatar.variant(resize: "100x100!"), class: "rounded-circle"
else
image_tag 'default_avatar.jpg', height: 100, width: 100, class: "rounded-circle"
end
end
With this (expected)...
undefined local variable or method `user'
I've tried multiple combinations
def tweets_index_avatar(image_tweet)
if tweet.user.avatar.attached?
image_tag tweet.user.avatar.variant(resize: "100x100!"), class: "rounded-circle"
else
image_tag 'default_avatar.jpg', height: 100, width: 100, class: "rounded-circle"
end
end
Error
undefined local variable or method `tweet' for
Or...
def tweets_index_avatar(image_tweet)
if tweet.user_id.avatar.attached?
image_tag tweet.user_id.avatar.variant(resize: "100x100!"), class: "rounded-circle"
else
image_tag 'default_avatar.jpg', height: 100, width: 100, class: "rounded-circle"
end
end
Same result
My avatars work fine outside my iteration but how would I get them working inside my 'each' iteration? ty
解决方案
It seems you are passing incorrect param(@image_tweet is not defined) to helper method. I assume you want to do it as following.
My view
<% @tweets.reverse.each do |tweet| %>
<strong><%= link_to tweet.user.email, thisuser_path(tweet.user_id) %></strong>
<br>
<%= tweets_index_avatar(tweet) %>
....
<% end %>
My helper
def tweets_index_avatar(tweet)
if tweet.user.avatar.attached?
image_tag tweet.user.avatar.variant(resize: "100x100!"), class: "rounded-circle"
else
image_tag 'default_avatar.jpg', height: 100, width: 100, class: "rounded-circle"
end
end
推荐阅读
- arrays - 如何使用 SOI 和 Nino 3.4 数据进行关联
- javascript - nodejs - jwt 身份验证后 res.render 不起作用
- covariance-matrix - 我不能在我的 R 中使用 matern.cov 函数
- android - 如何以编程方式检测应用程序是否自动更新?
- gps - FIWARE:CrateDB 上的 GPS 数据和 GRAFANA 上的可视化
- node.js - 有没有办法在 nodemailer 中使用 gmail 可以完美运行?
- kubernetes-helm - helm chart install 如何设置地图?
- php - 按组 php 循环求和
- r - 如何在 R 中确定给定时间段内出现多少索引的计数?
- nginx - Nginx:404 Not Found错误作为反向代理