【问题标题】:undefined method `content_for' in presenter rails演示者导轨中未定义的方法“content_for”
【发布时间】:2015-05-08 06:02:40
【问题描述】:

我在 Rails 中使用演示器来显示保存在 yml 文件中的数据。 (i18n 宝石)

这是控制器-

class DocumentsController < ApplicationController
  def index
    @presenter = DocumentPresenter.new
  end
end

这是我的看法-

= @presenter.viewname

这是我的主持人-

class DocumentPresenter
  def viewname
    content_for :secondary_nav_title do
      t('Documents')
    end
  end
end

错误提示:

未定义的方法`content_for'

为什么 rails 不能识别演示者中的content_for

【问题讨论】:

    标签: ruby-on-rails ruby web


    【解决方案1】:

    不应在您的模型中使用 content_for 辅助方法,因为这违反了 MVC 模式。

    如果你必须使用它,虽然不推荐,但你可以将它添加到模型的底部。

    def helpers 
        ActionController::Base.helpers
    end
    

    然后调用 content_for 你会使用

    class DocumentPresenter
      def viewname
          helpers.content_for :secondary_nav_title do
             t('Documents')
          end
      end
    end
    

    【讨论】:

    • 我没有在模型中使用 content_for。我在我的演示者中使用它。问题似乎出在演示者身上。由于某种原因,Rails 无法识别演示者中的 content_for。我说的对吗?
    • 这个解决方案应该仍然有效,尝试在演示者的末尾添加 def 助手并以上面显示的方式调用它
    • 效果很好。当我尝试通过 t('Documents') 访问这些值时,似乎仍然存在问题。我是否也需要为此添加助手?
    猜你喜欢
    • 2012-11-12
    • 1970-01-01
    • 2011-04-07
    • 1970-01-01
    • 1970-01-01
    • 2013-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多