Beruflich Dokumente
Kultur Dokumente
Note: Working code for the Events App available here https://github.com/gnaroji/Events-
Application
Add Events
Scaffold for events
script/generate scaffold event title:string description:string start_date:date end_date:date
user_id:integer
Run the migration
rake db:migrate
Add Users
Scaffold for Users
script/generate scaffold user first_name:string last_name:string login:string email:string
persistence_token:string crypted_password:string password_salt:string
Associate an event with a user
(# app/models/event.rb)
--------------------------------CODE-----------------------------
belongs_to :user
--------------------------------CODE-----------------------------
Add a user_id field to the events model
script/generate migration AddUsersToEvents user_id:integer
<p>
<%= f.submit 'Create User' %>
</p>
<% end %>
def new
@user_session = UserSession.new
end
def create
@user_session = UserSession.new(params[:user_session])
if @user_session.save
flash[:notice] = "You have logged in successfully!"
redirect_to root_url
else
render :action => :new
end
end
def destroy
current_user_session.destroy
flash[:notice] = "You have logged out successfully!"
redirect_to root_url
end
--------------------------------CODE-----------------------------
private
def current_user_session
return @current_user_session if defined?(@current_user_session)
@current_user_session = UserSession.find
end
def current_user
return @current_user if defined?(@current_user)
@current_user = current_user_session && current_user_session.record
end
def require_user
unless current_user
flash[:notice] = "Please sign in to access this page"
redirect_to root_url
return false
end
end
def require_no_user
if current_user
flash[:notice] = "Please sign out to access this page"
redirect_to root_url
return false
end
end
--------------------------------CODE-----------------------------