简体   繁体   中英

How to render a view from a view using a condition?

I'm testing out RoR and am currently trying to figure out the functionality which allows users with a valid session to skip logging in.

The login button usually prompts you to a login page, whereas I want to make it so that people with a session skip it and immediately get redirected to the show view using a conditional statement. (Checks via current_user) (If you need any other code just comment)

Here's the login view

<%= form_for :session, url: '/login' do |s| %>
<%= s.text_field :username, :placeholder => 'Username' %>
<%= s.password_field :password, :placeholder => 'Password' %>
<%= s.submit "Login" %>

<% if current_user %>
    <!-- What do i write here? -->
    <!-- Maybe I should put this in a controller? -->
    <% end %>

<% if flash[:notice] && current_user %>
    <div class="notice"><%= flash[:notice] %></div>
<% end %>

Here's the application controller containing the current_user function. (just in case)

class ApplicationController < ActionController::Base
protect_from_forgery with: :exception

helper_method :current_user

 def current_user
   @current_user ||= User.find_by(id: session[:id]) if session[:id]
 end
end

Not sure what your SessionsController looks like, but you could add something like this:

class SessionsController < ActionController::Base
  before_action :check_current_user

  def check_current_user
    redirect_to :root, success: "You are already logged in." if current_user
  end
end

Then you can remove the if current_user statement in your login view. And for your login links you could write:

<%= link_to 'Login', new_session_path unless current_user %>

This way the login button only shows if current_user is nil.

Also, take a look at Rails Tutorial Chapter 8: Basic Login for more information

Within your view you can render partials with the render method if you just want to show the login button to users that are not logged in:

<% unless current_user %>
  <%= render 'login_form' %>
<% end %>

Then you need to have a file named '_login_form' in your view directory:

<%= form_for :session, url: '/login' do |s| %>
<%= s.text_field :username, :placeholder => 'Username' %>
<%= s.password_field :password, :placeholder => 'Password' %>
<%= s.submit "Login" %>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM