ej96 ej96 - 4 months ago 9
Ruby Question

Why is this method undefined if its an attribute of my model?

I'm trying to access the field of a ruby object. Here is my code.

<% if @statuses %>
<% @statuses.each do |status| %>
<div class="well">
<%= status.content %>
<br></br>

<%= user = User.find_by_profile_name(params[:id]) %>
<br></br>

<% @profile_user = User.find(status.tag_list).first %>
<%= link_to @profile_user.profile_name, user_profile_path(@profile_user.profile_name) %>


<br></br>
<%= status.user.full_name %>
<hr />
<%= link_to time_ago_in_words(status.created_at), status_path(status) %> ago
</div>
<% end %>
<% end%>


at this line

<%= link_to @profile_user.profile_name, user_profile_path(@profile_user.profile_name) %>


i get this error message

undefined method `profile_name' for #< Array:0x007fe265c40410>

does anyone know what I'm doing wrong?

EDIT:

this is my user model

class User < ApplicationRecord
rolify
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable

validates :first_name, presence: true

validates :last_name, presence: true

validates :profile_name, presence: true, uniqueness: true,
format: {
with: /\A[a-zA-Z0-9_-]+\z/,
message: 'Must be formatted correctly'
}

has_many :statuses

def full_name
first_name + " " + last_name
end

def gravatar_url
stripped_email = email.strip
downcased_email =stripped_email.downcase
hash = Digest::MD5.hexdigest(downcased_email)

"http://gravatar.com/avatar/#{hash}"
end

end

Answer

From the docs:

Person.find([1])     # returns an array for the object with ID = 1

Presumably, status.tag_list is an array, so when you pass it to User#find, you're getting an array back in response. This array doesn't have a profile_name method, which is why you're seeing a NoMethodError.

I can't be sure what your intentions are here, so either:

  • pass a specific ID to User#find in order to get a single User back in response

  • use first/last to pull a specific user out of your call to User#find. Something like, @profile_user = User.find(status.tag_list).first

  • iterate over the array in @profile_user when rendering the links, in case you're actually expecting multiple Users.

Comments