1

Is it possible to get the user_path in the User model? I'm trying to implement the following method:

def link_path
   link_to self.name, user_path(self.id_
end

But i'm getting that user_path is undefined. Any ideas?

Aloke Desai
  • 919
  • 7
  • 16
  • 26
  • Yes this is correct, should have seen this. My apologies. – Aloke Desai Jun 16 '14 at 22:17
  • Don't apologize, elaborate. *Why* do you think, you need the URL helper in your model? – DMKE Jun 16 '14 at 22:55
  • @user1596679 While there may be duplicates of your question, don't accept the answer in that thread without first considering using helpers. A lot of people are ignoring "the rails way" here... – Matt Jun 17 '14 at 08:07

2 Answers2

1

How about ...

def link_path
  Rails.application.routes.url_helpers.user_path(self)
end

I've done this sort of thing in APIs - where I want the url to the site to be in the json of the API response.

Mark Swardstrom
  • 15,663
  • 5
  • 57
  • 62
0

That kind of method usually sits in a helper:

UsersHelper.rb

def user_link_path(user)
  link_to user.name, user_path(user)
end

View:

<%= user_link_path(user) %>

You can use url helpers in your models if you really want to, but I don't see any reason to for what you're doing, so may as well do it the rails way.

Community
  • 1
  • 1
Matt
  • 13,121
  • 6
  • 42
  • 63