【问题标题】:RoR: Displaying active storage images within an 'each' iteration?RoR:在“每次”迭代中显示活动存储图像?
【发布时间】:2020-08-07 03:42:46
【问题描述】:

我正在尝试在推文循环中显示用户个人资料图片。

我的模型

user.rb
has_many :tweets

tweet.rb
belongs_to :user, optional: true

我的看法

<% @tweets.reverse.each do |tweet| %>
    <strong><%= link_to tweet.user.email, thisuser_path(tweet.user_id) %></strong>
    <br>
    <%= tweets_index_avatar(@image_tweet) %>

   ....

 <% end %>

我的助手

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

有了这个(预期的)......

undefined local variable or method `user'

我尝试了多种组合

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

错误

undefined local variable or method `tweet' for 

或者……

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

同样的结果

我的头像在我的迭代之外工作正常,但我如何让它们在我的“每个”迭代中工作? 太棒了

【问题讨论】:

  • 什么是@image_tweet
  • “我的头像在外面也能正常工作”是什么意思?
  • 在“每个做”迭代之外。 ("@.....") 是适用于我的助手的语法

标签: ruby-on-rails rails-activestorage


【解决方案1】:

您似乎将不正确的参数(@image_tweet 未定义)传递给辅助方法。我假设您想按以下方式进行操作。

我的看法

  <% @tweets.reverse.each do |tweet| %>
    <strong><%= link_to tweet.user.email, thisuser_path(tweet.user_id) %></strong>
    <br>
    <%= tweets_index_avatar(tweet) %>

   ....

  <% end %>

我的助手

  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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-01
    相关资源
    最近更新 更多