Rails path helper not recognized in model

In my rails application, I have a command model. My route.rb file for commands is as follows:

resources :teams 

In the teams_controller.rb file, the line team_path(Team.first.id) works, however the team_path URL team_path not recognized in my model.rb command. 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 .

+10
ruby ruby-on-rails ruby-on-rails-4
source share
4 answers

You should be able to call url_helpers as follows:

 Rails.application.routes.url_helpers.team_path(Team.first.id) 
+16
source share

Consider solving 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" 

For the Team model from the question, try the following:

 # 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 method that I prefer as it adds fewer models to the model.

Avoid include and use url_helpers from the routes object:

 class Team < ActiveRecord::Base delegate :url_helpers, to: 'Rails.application.routes' def base_uri url_helpers.team_path(self) end end 
+7
source share

to add to the previous answer, you can use Rails.application.routes.url_helpers , just add :as to the route, as in the following example:

 get "sessions/destroy/:param_id", as: :logout 

so you can use it like this:

 Rails.application.routes.url_helpers.logout_path(:param_id => your_value) 

Hope this helps

0
source share

Models should not deal with things like paths, redirects, or any other things. These things are pure constructions of a view or controller.

The model really should be just that; model of what you are creating. He should fully describe this thing, allow you to find copies of it, make changes to it, perform checks on it ... But this model would not have a clue about which path should be used for anything, even for yourself.

Usually in the Rails world it is said that if it is difficult for you to do something (for example, to call the path helper from the model), you are doing it wrong. This means that even if something is possible, if it is difficult to do in Rails, it is probably not the best way to do it.

-one
source share

All Articles