Search code examples
ruby-on-railsrails-activestorage

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


Solution

  • 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