简体   繁体   English

Rails的未定义局部变量或方法错误

[英]undefined local variable or method error with rails

I have a method in controller - 我在控制器中有一个方法-

def undo_link
  view_context.link_to("undo", revert_version_path(@page.versions.scoped.last), :method => :post)
end

But when i call it in views with "#{undo_link}" . 但是当我在视图中使用"#{undo_link}"调用它时。 I get the undefined local variable or method error . 我得到未定义的局部变量或方法错误。

what am i doing wrong ? 我究竟做错了什么 ?

Update : Here the revert method in the controller 更新:这里是控制器中的还原方法

okay but then this is the revert method i got in the controller 好的,但这是我在控制器中得到的还原方法

def revert
  @version = Version.find(params[:id])
  if @version.reify
    @version.reify.save!
  else
    @version.item.destroy
  end
  link_name = params[:redo] == "true" ? "undo" : "redo"
  link = view_context.link_to(link_name, revert_version_path(@version.next, :redo => !params[:redo]), :method => :post)
  redirect_to :back, :notice => "Undid #{@version.event}. #{link}"
end

As Dave Newton said in the comments (+1), this belongs in a helper. 正如戴夫·牛顿(Dave Newton)在评论(+1)中说的那样,这属于帮手。

in helpers/pages_helper.rb : helpers/pages_helper.rb

module PagesHelper
  def undo_link
    # ...define view_context here...
    view_context.link_to("undo", revert_version_path(@page.versions.scoped.last), :method => :post)
  end
end

Note that you will need to define view_context before this will work, either in the space indicated, passing it in as an argument, or by using an instance variable accessible to the view at the time the helper method is called. 请注意,您需要先定义view_context然后才能在指示的空间中定义,将其作为参数传递或通过使用调用辅助方法时视图可访问的实例变量。

To call it in a view: 要在视图中调用它:

<%= undo_link %>

If you do this... 如果你这样做

"#{undo_link}"

...you will get this: ...您将获得:

 "<a href="/revert/version/path/...">undo</a>" # <= surrounded by quotes!

which will not work . 这将无法正常工作

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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