mercredi 7 juin 2017

How to bind a form of a register to the User object? - Rails

I have a Model called user and a controller called login which have one view called new.html.erb. On the view "new", I have a small form to make the user registration but I really don't know how use the form helpers to deal with it. I was reading the http://ift.tt/2s4mHts but its getting cofuse to me... I am a bachelors student in information systems!

Login controller:

class LoginController < ApplicationController
  skip_before_action :verify_authenticity_token

  def new
    if session[:user]
      if User.exists?
        session.destroy
      end
      if @user.nil?
        session.destroy
        redirect_to new_login_path
      end
    end
  end

  def destroy
    redirect_to "/login/acesso", notice: "Você foi deslogado"
  end

  def create
    user = User.validate(login_params[:email], login_params[:senha])
    if user
      session[:user] = user.id
      redirect_to "/home/inicio", notice: "login feito com sucesso"
    else
      redirect_to "/login/acesso", notice: "Dados incorretos"
    end

  end
  private
  def login_params
    params.require(:login).permit(:email, :senha)
  end
end

The new.html.erb (i'm trying to do something like this...):

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

<%= form_with(model: user, local: true) do |form| %>
    <% if user.errors.any? %>
        <div id="error_explanation">
          <h2><%= pluralize(produto.errors.count, "error") %> prohibited this produto from being saved:</h2>

          <ul>
            <% user.errors.full_messages.each do |message| %>
                <li><%= message %></li>
            <% end %>
          </ul>
        </div>
    <% end %>

    <div class="field">
      <%= form.label :nome %>
      <%= form.number_field :nome, id: :user_nome %>
    </div>

    <div class="field">
      <%= form.label :email %>
      <%= form.text_field :email, id: :user_email %>
    </div>

    <div class="field">
      <%= form.label :senha %>
      <%= form.text_field :senha, id: :user_senha %>
    </div>

    <div class="actions">
      <%= form.submit %>
    </div>
<% end %>

The User Model:

class User < ApplicationRecord
  def self.validate(email,senha)
    User.find_by(email:email, senha: Digest::MD5.hexdigest(senha))
  end
end

Aucun commentaire:

Enregistrer un commentaire