【问题标题】:Unable to figure out NameError on local variable [duplicate]无法找出局部变量上的 NameError [重复]
【发布时间】:2014-07-01 06:44:18
【问题描述】:

我的 application_helper.rb 文件有以下代码

module ApplicationHelper
def current_user
      @current_user ||= User.find(session[:user_id]) if session[:user_id]
    end
end

我有一个带有方法的帖子控制器

def create
@post = Post.new(params[:post])
@post.posted_by_uid=current_user.id
@post.posted_by=current_user.first_name+" "+current_user.last_name
@post.ups=0
@post.downs=0
@post.save
respond_to do |format|
    if @post.save
        format.html {redirect_to root_path}
        format.json {render :json => @post, :status => :created, :location => @post}
    else
        format.html {redirect_to root_path}
        format.json {render :json => @post.errors, :status => :unprocessable_entity }
    end
end
end

但是当我尝试通过以下视图提交表单时

<%= form_for(@post) do |f| %>
<div class="fields">
<%= f.label "Post" %><br />
<%= f.text_field :post %>
</div>
<div class="actions" id="refreshposts">
<%= f.submit("Post") %>
</div>
<% end %>

它返回一个错误未定义的局部变量或方法`current_user'

感谢任何帮助

【问题讨论】:

  • 该错误出现在哪一行?
  • @Pavan in app/controllers/posts_controller.rb:36:in `create' 这是@post.posted_by_uid=current_user.id

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


【解决方案1】:

ApplicationController 类中包含ApplicationHelper 模块,以便控制器中可以使用current_user 方法。

class ApplicationController < ActionController::Base
  include ApplicationHelper ## Add this line
  ## ...
end

【讨论】:

  • 哇,你的声望这么高,这么快!恭喜;)
  • 你又回来了!很高兴看到:)
  • @Pavan 我天气不好。但我现在回来了。你又遇到了竞争。 :D
  • 是的!你对我来说非常有竞争力。但我肯定会试一试:)
  • @KirtiThorat Ahah 不,当我看到你的进步时,我不敢和你竞争!当我们开始时,你是 6 或 7k 代表,而不是 15.2K !!
猜你喜欢
  • 1970-01-01
  • 2014-08-07
  • 2021-08-02
  • 1970-01-01
  • 1970-01-01
  • 2013-08-19
  • 1970-01-01
  • 2023-03-05
  • 1970-01-01
相关资源
最近更新 更多