ruby-on-rails Rails:未定义的本地变量或方法`view_context' for #< ActionView::Base:0x007f8091a1cb88>

fykwrbwg  于 2023-04-08  发布在  Ruby
关注(0)|答案(1)|浏览(120)

我有一个名为FeaturesHelper的助手,它有一些特性的数据:

feature_info = [
    {features:
        [
            {
                description: "This is a #{view_context.link_to "link!", "https://www.example.com", target: :_blank, class: "pink-link"}", 
            }
        ]
}, ...]

然后我有一个使用feature_info的部分:

<% feature_info.each do |info|%>    
    <% info[:features].each do |feature| %>
        <%= feature[:description].html_safe %>                               
    <% end %>
<% end %>

然后我在视图中渲染部分:

<%= render partial: "partial_name" %>

这会导致堆栈跟踪指向no my FeaturesHelper的错误:

ActionView::Base:0x007f80a6cdcf20的未定义局部变量或方法`view_context'

tquggr8v

tquggr8v1#

view_context在这里是不可见的,你需要将它作为参数传递。

module FeaturesHelper
  def self.feature_info(view_context)
    [
      {
        features: [
          {
            description: "This is a #{view_context.link_to 'link!', 'https://www.example.com', target: :_blank, class: 'pink-link'}",
          }
        ]
      }, # ...
    ]
  end
end

在你看来:

<% feature_info = FeaturesHelper.feature_info(view_context) %>

<% feature_info.each do |info| %>
  <% info[:features].each do |feature| %>
    <%= feature[:description].html_safe %>
  <% end %>
<% end %>

相关问题