3

这是我会话的控制器代码

  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

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

有人可以帮忙吗?

4

3 回答 3

2

在应用程序布局中

<% if session[:user_id].nil? %>
  <div id="welcomebuttons">
  </div>
<% end %>
于 2011-07-23T06:12:34.010 回答
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 %>
于 2011-07-23T08:19:47.593 回答
0

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

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

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

<% if current_user %>
    <div>  <%= "Logged in as #{current_user.email}" %> | <%= link_to 'Home', root_path %> | <%= link_to 'Log Out', logout_path, method: :delete %> </div>
    <% else %>
     <div> <%= link_to 'Home', root_path %> | <%= link_to 'Log In', login_path %> or <%= link_to 'Sign Up', new_user_path %> </div>
    <% end %>
于 2020-03-19T19:18:18.220 回答