Skip to content

Instantly share code, notes, and snippets.

@anlek
Created May 5, 2010 17:57
Show Gist options
  • Save anlek/391181 to your computer and use it in GitHub Desktop.
Save anlek/391181 to your computer and use it in GitHub Desktop.
class Group < ActiveRecord::Base
has_many :users
def email_regex
#This can be generated here or pulled from a database
end
end
ActionController::Routing::Routes.draw do |map|
map.resources :groups, :has_many => :users
map.resources :users, :except => [:new, :create] #This is so that the user can't be created unless going through a group
#Other routes down here.
end
class User < ActiveRecord::Base
belongs_to :group
validates_presence_of :group_id
def validate
errors.add(:email, "Your error message here") if !group || group.email_regex ~= self.email
end
end
class UsersController < ApplicationController
#only showing new, but you'll most likely have index, show, edit, destroy and all those
def new
@user = current_group.users.new
end
def create
@user = current_group.users.new(params[:user])
if @user.save
flash[:notice] = "#{@user.full_name} created successfully"
redirect_to(users_path)
else
flash[:error] = "We couldn't set up that account, sorry. Please try again, or contact an admin (link is above)."
render :action => 'new'
end
end
private
def current_group
@current_group ||= Group.find(params[:group_id])
#this will raise an error if no group is found, so you might want to catch that
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment