ruby on rails - can't create my @current_user -
i'm new in ruby on rails, help me? i can't see @current_user.username
*this session_controller
class sessioncontroller < applicationcontroller def new end def create user = user.find_by_username(params[:session][:username]) if user login user redirect_to user else render 'new' end end def sucess end def error end end
*sessionhelper
module sessionhelper def login(user) session[:user_id] = user.id end def current_user @current_user ||= user.find(session[:user_id]) end end
*controller
class applicationcontroller < actioncontroller::base protect_from_forgery with: :exception include sessionhelper end
*my model user
class user < activerecord::base attr_accessible :pass, :username validates :username, :pass, :presence => true validates :username, :pass, :length => { :minimum => 4 } validates :username, :uniqueness => true
*application layout
<title>sessions</title> <%= stylesheet_link_tag "application", :media => "all" %> <%= javascript_include_tag "application" %> <%= csrf_meta_tags %> </head> <body> <% if @current_user %> hello <%= @current_user.username %> <% end %> <%= yield %> </body>
*and login view
<%= form_for(:session, url: login_path) |f| %> <%= f.label :username %> <%= f.text_field :username %> <%= f.label :pass %> <%= f.password_field :pass %> <%= f.submit "log in" %> <% end %>
please help me :)
you have method in helper:
def current_user @current_user ||= user.find(session[:user_id]) end
so in templates should utilize current_user
rather @current_user
so, should be:
<body> <% if current_user %> hello <%= current_user.username %> <% end %> <%= yield %> </body>
update:
but it's improve create method in applicationcontroller
:
def current_user @current_user ||= user.find(session[:user_id]) if session[:user_id] end helper_method :current_user
because in case current_user
can called controllers , templates well.
ruby-on-rails ruby
No comments:
Post a Comment