简体   繁体   中英

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.

您应该能够以这种方式调用url_helpers:

Rails.application.routes.url_helpers.team_path(Team.first.id)

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

Models are not supposed to be dealing with things like paths, redirects or any of that stuff. Those things are purely constructions of the view or the controller.

The model really should be just that; a model of the thing that you are creating. It should fully describe this thing, allow you to find instances of it, make changes to it, perform validations upon it... But that model wouldn't have any notion of what path should be used for anything, even itself.

A common saying in the Rails world is that if you're finding it difficult to do something (like call a path helper from a model) you are doing it wrongly. Take this to mean that even if something is possible, if it is hard to do in Rails it is likely not the best way to do it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM