user12509056
user12509056

Reputation:

Why can't I include dynamic image_tag in HTML?

I am trying to display an image in Rails with image_tag so it can dynamically change based on if the user has an avatar attached to their account, but I keep getting an error for <% if resource.avatar.attached?. It also states

"undefined local variable or method `resource' for #<#:0x0000561b852e6890> Did you mean? rescue"

I don't know what is causing this, what can I do to fix this?

Error

<div>
  <% if resource.avatar.attached? %>
    <%= image_tag @user.avatar, class:"rounded-circle" %>
  <% else %>
    <%= image_tag("fallback/default-avatar.png", class:"rounded-circle") %>
  <% end %>
</div>

Upvotes: 0

Views: 77

Answers (1)

mechnicov
mechnicov

Reputation: 15298

The problem is that resource is undefined.

Just change resource to @user:

<div>
  <% if @user.avatar.attached? %>
    <%= image_tag @user.avatar, class:"rounded-circle" %>
  <% else %>
    <%= image_tag("fallback/default-avatar.png", class:"rounded-circle") %>
  <% end %>
</div>

But it's better to make helper like this:

module AvatarHelper
  def avatar(resource)
    if resource.avatar.attached?
      image_tag resource.avatar, class: "rounded-circle"
    else
      image_tag "fallback/default-avatar.png", class: "rounded-circle"
    end
  end
end

Then just add this code in your view:

<div><%= avatar(@user) %></div>

And it's good practice to make alt attribute in the img tag.

Upvotes: 2

Related Questions