0

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

3
  • What is @image_tweet? Commented Aug 6, 2020 at 19:26
  • Also what do you mean by "my avatars work fine outside"? Commented Aug 6, 2020 at 19:28
  • Outside of "each do" iterations. ("@.....") is the syntax that works for me with my helpers Commented Aug 6, 2020 at 19:32

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.