Skip to content

Instantly share code, notes, and snippets.

@matt297
Last active June 7, 2017 23:08
Show Gist options
  • Save matt297/4c0175a2df38fda557f2b09225370535 to your computer and use it in GitHub Desktop.
Save matt297/4c0175a2df38fda557f2b09225370535 to your computer and use it in GitHub Desktop.
Lighthouse Labs - Intro to Web Dev - W4D2 - May 2017 Cohort

app/models/user.erb

class User < ActiveRecord::Base

  # All of the fields listed here are required
  validates_presence_of :email, :avatar_url, :username, :password

  # All of these fields must be unique (i.e. can't register the same email twice)
  validates_uniqueness_of :email, :username
  
 end

app/views/register.erb

<% if @user.present? && @user.errors.present? %>
  Error! The following errors prevented saving:
  <ul>
    <% @user.errors.full_messages.each do |error| %>
      <li><%= error %></li>
    <% end %>
  </ul>
<% end %>

<form method="post">
    
    <label for="email">Email:</label>
    <input type="email" name="email" id="email" required>
    
    <br><br>
    
    <label for="username">Username:</label>
    <input type="text" name="username" id="username" required>
    
    <br><br>
    
    <label for="avatar_url">Avatar URL:</label>
    <input type="url" name="avatar_url" id="avatar_url" required>
    
    <br><br>
    
    <label for="password">Password:</label>
    <input type="password" name="password" id="password" required>
    
    <br><br>
    
    <input type="submit">
    
</form>

app/actions.rb

get '/register' do
  erb :register
end

post '/register' do
  # Get the values the user submitted in the form
  email = params[:email]
  username = params[:username]
  avatar_url = params[:avatar_url]
  password = params[:password]
  
  # Create a new instance of the user class
  @user = User.new(email: email, username: username, avatar_url: avatar_url, password: password)
  
  # Try saving the user to the database
  # Remember that .save automatically runs validations and returns true or false
  if @user.save
    # Saving worked, so render a success page!
    erb :registration_complete
  else
    # Saving did not work, show registration form again with errors
    erb :register
  end
end

app/views/registration_complete.erb

<p>
  Hey there <%= @user.username %>,
</p>
<p>
  Thanks for registering, you're all set! Enjoy the fins.
</p>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment