在Rails中,当用户登录时隐藏一个div

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

我需要一个div,它的id是"welcomebuttons",它应该在layouts/application.html.erb中显示,当用户未登录时(登出)而完全消失和保持隐藏,当用户已登录时。我尝试将javascript:hideDiv_welcomebuttons()添加到if user中,但当然没有起作用。
有人能帮忙吗?
3个回答

2
在应用程序布局中
<% if session[:user_id].nil? %>
  <div id="welcomebuttons">
  </div>
<% end %>

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

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接