Question

My application_helper.rb file has the following code

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

and I have a posts controller which has a method

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

However when I try to submit a form by the following view

<%= 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 %>

it returns an error undefined local variable or method `current_user'

Any help is appreciated

Was it helpful?

Solution

Include ApplicationHelper module in ApplicationController class so that current_user method would be available in the controllers.

class ApplicationController < ActionController::Base
  include ApplicationHelper ## Add this line
  ## ...
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top