Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rails path helper not recognized in model

In my rails application I have a teams model. My route.rb file for teams looks like this:

resources :teams

In my teams_controller.rb file the line team_path(Team.first.id) works however the team_path url helper is not recognized in my model team.rb. I get this error message:

 undefined local variable or method `team_path' for # <Class:0x00000101705e98>
 from /usr/local/rvm/gems/ruby-1.9.3-p392/gems/activerecord-4.1.1/lib/active_record/dynamic_matchers.rb:26:in `method_missing'

I need to find a way for the model to recognize the team_path path helper.

like image 519
user3266824 Avatar asked Feb 14 '15 22:02

user3266824


2 Answers

Consider solving this as suggested in the Rails API docs for ActionDispatch::Routing::UrlFor:

# This generates, among other things, the method <tt>users_path</tt>. By default,
# this method is accessible from your controllers, views and mailers. If you need
# to access this auto-generated method from other places (such as a model), then
# you can do that by including Rails.application.routes.url_helpers in your class:
#
#   class User < ActiveRecord::Base
#     include Rails.application.routes.url_helpers
#
#     def base_uri
#       user_path(self)
#     end
#   end
#
#   User.find(1).base_uri # => "/users/1"

In the case of the Team model from the question, try this:

# app/models/team.rb
class Team < ActiveRecord::Base
  include Rails.application.routes.url_helpers

  def base_uri
    team_path(self)
  end
end

Here is an alternative technique which I prefer as it adds fewer methods to the model.

Avoid the include and use url_helpers from the routes object instead:

class Team < ActiveRecord::Base

  delegate :url_helpers, to: 'Rails.application.routes'

  def base_uri
    url_helpers.team_path(self)
  end
end
like image 107
Eliot Sykes Avatar answered Nov 09 '22 16:11

Eliot Sykes


You should be able to call the url_helpers this way:

Rails.application.routes.url_helpers.team_path(Team.first.id)
like image 21
trosborn Avatar answered Nov 09 '22 15:11

trosborn