ej96 ej96 - 1 year ago 70
Ruby Question

Why is this method undefined if it's an attribute of my model?

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

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

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

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

<%= status.user.full_name %>
<hr />
<%= link_to time_ago_in_words(status.created_at), status_path(status) %> ago
<% 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>

This is my user model:

class User < ApplicationRecord
# 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

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



Does anyone know what I'm doing wrong?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download