rails path helper在模型中无法识别

use*_*824 10 ruby ruby-on-rails ruby-on-rails-4

在我的rails应用程序中,我有一个团队模型.我的团队的route.rb文件如下所示:

resources :teams
Run Code Online (Sandbox Code Playgroud)

在我的teams_controller.rb文件中,该行team_path(Team.first.id)有效但team_path在我的模型team.rb中无法识别url助手.我收到此错误消息:

 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'
Run Code Online (Sandbox Code Playgroud)

我需要找到一种方法让模型识别team_path路径助手.

tro*_*orn 16

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

Rails.application.routes.url_helpers.team_path(Team.first.id)
Run Code Online (Sandbox Code Playgroud)

  • 当然不是"The Rails Way". (3认同)
  • 它绝对适合模型负责了解自己的位置,即URL.对于与CMS相关的模型,例如"Page","Article"等,这两者都是如此,但对于任何具有URL知识的模型来说都是如此. (3认同)

Eli*_*kes 8

考虑按照Rails API文档中的建议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"
Run Code Online (Sandbox Code Playgroud)

对于Team问题中的模型,请尝试以下方法:

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

  def base_uri
    team_path(self)
  end
end
Run Code Online (Sandbox Code Playgroud)

这是一种我更喜欢的替代技术,因为它为模型添加了更少的方法.

避免include并用url_helpersroutes替代对象:

class Team < ActiveRecord::Base

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

  def base_uri
    url_helpers.team_path(self)
  end
end
Run Code Online (Sandbox Code Playgroud)