ruby on rails - Call model method from different view -
i have model method
def full_name_find(user_id) user = user.find(user_id) "#{user.first_name} #{user.last_name}" end that in user model. call view (tickets#show) , can't seem work.
i tried:
<%= user.full_name_find(comment.user_id) %> where comment has user_id. undefined method 'full_name_find' #<class:0x007fd188e41108>. can work when stick full_name_find method applications helper , call in view as:
<%= full_name_find(comment.user_id) %> and works. advice?
you make work making class method, i.e. putting self. before 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. doesn't make sense doing database operation (user.find) in method that's supposed return user's name. more idiomatic approach simple instance method, enable full name user instance:
class user < activerecord::base # ... def full_name "#{first_name} #{last_name}" end end then, in view:
<%= comment.user.full_name %> this better reason above (not mention being lot simpler), because when load comments can use includes eager-load associated users (e.g. comment.where(...).includes(:user)), don't have whole bunch of additional database requests users' names.
Comments
Post a Comment