assign events on creation of a new user

Hello everyone,

I am developing a web app that is being used to track users and their
associated events. Events could be like 'getting married', 'having a
baby', 'buying a car', etc. and each event has a median age associated
with it. For instance the getting married median age is 25.

I have the application working with checkboxes where you can click
edit on a user and see all the possible events listed and the events
that are associated with that user have a check in the checkbox next
to the event.

See screen shot here:

I am using a join model called occurrence.

the new task I am faced with is upon the creation of a new user I
would like to auto associate all events with them based on the user's
age and the ages defined in the events. Eventually I would like to
have it so that you can be within 5 years on either side of the median
age defined for the event and it will auto associate upon creation of
a new user.

Here is some of my code...

I was trying to get it to work with a callback in the user model
called 'before_save :assign_age_items'

class User < ActiveRecord::Base
  has_many :occurrences, :dependent => :destroy #, :conditions =>
"enabled = 1"
  has_many :events, :through => :occurrences

  before_save :assign_age_items

  validates_uniqueness_of :username, :on => :create, :message => "must
be unique"
  validates_presence_of :username, :on => :create, :message => "can't
be blank"
  validates_presence_of :password, :on => :create, :message => "can't
be blank"
  validates_presence_of :email, :on => :create, :message => "can't be
  validates_presence_of :fname, :on => :create, :message => "can't be
  validates_presence_of :lname, :on => :create, :message => "can't be
  validates_presence_of :gender, :on => :create, :message => "can't be

  ###### This doesn't work
  attr_reader :user

  def initialize(user)
    @user = user

Anyone have anything on this?

Thanks in advance...

You might want to look into ActiveRecord’s callbacks or Observers. :slight_smile:


I understand I should be using a callback, in fact I am using one in
the code that I provided for this post. I'm using the before_save
callback to well call back a function called 'def assign_age_items' My
problem is that I don't know how to get the into out of the user that
just passed their info via the params. My function 'def
assign_age_items' looks like this

def assign_age_items
    year =
    birthyear = @user.dob.year
    age = year - birthyear

    events << Events.find_by_age(age)

I just want to be able to associate all events that are within the
target user's age to the user.

I'm probably going about this all wrong but ActiveRecord is still my
biggest stumbling block with Rails. I've read literally all the
Pragmatic books and I understand most of the stuff but anytime I want
to deviate from a tutorial I find myself clueless as to how to get
ActiveRecord to do something that I don't have an exact code example