Cameron Aziz
Cameron Aziz

Reputation: 487

Call model method from different view

I have a model method

def full_name_find(user_id)
   user = User.find(user_id)
   "#{user.first_name} #{user.last_name}"
end

that is in the User model. I would like to call it from another view (tickets#show) and I can't seem to get it to work.

I tried:

<%= User.full_name_find(comment.user_id) %>

where comment has a user_id. I get undefined method 'full_name_find' for #<Class:0x007fd188e41108>. I only can get it to work when I stick the full_name_find method into the applications helper and call in view as:

<%= full_name_find(comment.user_id) %>

and it works. Any advice?

Upvotes: 1

Views: 1912

Answers (1)

Jordan Running
Jordan Running

Reputation: 106027

You could make it work by making it a class method, i.e. by putting self. before its name:

def self.full_name_find(user_id)
   user = find(user_id)
   "#{user.first_name} #{user.last_name}"
end

User.full_name_find(123)
# => "Jane Doe"

...but that's pretty weird. It doesn't make sense to be doing a database operation (User.find) in a method that's just supposed to return a user's name. A much more idiomatic approach would be a simple instance method, which will enable you to get the full name for any User instance:

class User < ActiveRecord::Base
  # ...
  def full_name
    "#{first_name} #{last_name}"
  end
end

Then, in your view:

<%= comment.user.full_name %>

This is much better for the reason above (not to mention being a lot simpler), but also because when you load your Comments you can use includes to eager-load the associated Users (e.g. Comment.where(...).includes(:user)), so you don't have to do a whole bunch of additional database requests to get the users' names.

Upvotes: 4

Related Questions