用户登录rails时隐藏div

时间:2011-07-23 06:04:22

标签: ruby-on-rails ruby session html logged

这是我的会话的控制器代码

  def create
    user = User.authenticate(params[:login], params[:password])
    if user
      session[:user_id] = user.id
      redirect_to_target_or_default root_url, :notice => "Logged in successfully."
    else
      flash.now[:alert] = "Invalid login or password."
      render :action => 'new'
    end
  end

我需要位于layouts / application.html.erb中的div id="welcomebuttons"来显示用户何时不在会话中(已注销)但在用户登录时完全消失并保持隐藏状态。我尝试添加javascript:hideDiv_welcomebuttons()if user,但当然没有用。

有人可以帮忙吗?

3 个答案:

答案 0 :(得分:1)

在应用程序布局中

<% if session[:user_id].nil? %>
  <div id="welcomebuttons">
  </div>
<% end %>

答案 1 :(得分:0)

我正在使用像这样的块帮助器(只是将它们添加到你的application_helper.rb并且你很高兴):

# application_helper.rb
def not_logged_in(&block)
  capture(&block) unless session[:user_id]
end

def logged_in(&block)
  capture(&block) if session[:user_id]
end

#application.html.erb
<div>I'm visible for everyone</div>

<%= logged_in do %>
  <div>I'm only visible if you are logged in</div>
<% end %>

<%= not_logged_in do %>
  <div>I'm only visible unless you are logged in</div>
<% end %>

答案 2 :(得分:0)

您在应用程序控制器中定义了current_user方法:

@Digits(integer = 2, fraction = 4)

,然后将其用作布局中if块的条件:

def current_user
# Look up the current user based on user_id in the session cookie:
#TIP: The ||= part ensures this helper doesn't hit the database every time a user hits a web page. It will look it up once, then cache it in the @current_user variable.
#This is called memoization and it helps make our app more efficient and scalable.
  @current_user ||= User.find(session[:user_id]) if session[:user_id]
end