【问题标题】:rails path helper not recognized in model模型中无法识别 rails path helper
【发布时间】:2015-02-14 22:12:53
【问题描述】:

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

resources :teams

在我的 teams_controller.rb 文件中,team_path(Team.first.id) 行有效,但我的模型 team.rb 中无法识别 team_path 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'

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

【问题讨论】:

  • 我认为您必须避免在模型中使用助手。助手在视图和控制器中很有用。无论如何,错误消息是什么,您将如何使用帮助程序?
  • 它们通常只对视图和控制器有用,但对于这种特殊情况,我需要模型中的路径助手。我从 /usr/local/rvm/gems/ruby-1.9.3-p392/gems/activerecord-4.1.1/lib/active_record/dynamic_matchers.rb 收到 #<0x00000101705e98>

标签: ruby-on-rails ruby ruby-on-rails-4


【解决方案1】:

您应该可以通过这种方式调用 url_helpers:

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

【讨论】:

  • 这肯定不是“Rails 方式”。
  • 模型负责知道自己的位置(即 URL)绝对没问题。对于PageArticle 等与 CMS 相关的模型来说更是如此,但对于任何有 URL 的模型来说都可以。
  • 感谢艾略特。我会听从您的良好判断并相应地编辑我的答案。
【解决方案2】:

考虑解决这个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"

对于问题中的Team 模型,试试这个:

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

  def base_uri
    team_path(self)
  end
end

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

避免使用include,而是使用routes 对象中的url_helpers

class Team < ActiveRecord::Base

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

  def base_uri
    url_helpers.team_path(self)
  end
end

【讨论】:

    【解决方案3】:

    模型不应该处理诸如路径、重定向或任何类似的东西。这些东西纯粹是视图或控制器的构造。

    模型真的应该是这样的;您正在创建的事物的模型。它应该完整地描述这个东西,允许你找到它的实例,对其进行更改,对其执行验证......但是那个模型不会有任何关于应该使用什么路径的概念,甚至它自己。

    Rails 世界中的一个常见说法是,如果您发现做某事很困难(例如从模型中调用路径助手),那么您就做错了。这意味着即使某事是可能的,如果在 Rails 中很难做到,那么它可能不是最好的方法。

    【讨论】:

    • 我正在尝试将不同团队的多个路径与团队的其他属性一起存储在 json 字符串中,并在将鼠标悬停在某个 html 元素上时将它们呈现到工具提示中。所以这不是典型的重定向情况。我在我的模型中创建了一个方法,它使用我的所有属性创建了这个 json 字符串。该链接是我刚刚想到的,我不确定如何在控制器中实现此逻辑而不在控制器中放置大量繁重的逻辑。对我来说,把它放在模型中是最有意义的。
    【解决方案4】:

    要添加上一个答案,您可以使用Rails.application.routes.url_helpers,只需添加路由:as,如下例所示:

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

    所以你可以如下使用它:

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

    希望这会有所帮助

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-07-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多