AnApprentice
AnApprentice

Reputation: 111090

Rails - Creating a notifications model for Users

I'm working to create a notifications model for my users in the app. Which emails they get etc.

I'm going to create a model UserNotifications, with a bunch of columns per setting that are binary.

What I haven't learned yet with Rails is, every user needs to have record in the UserNotifications Model. So how do I do the following:

  1. When a user is created, add a record for that user in the UserNotifications table?
  2. Handle all the existing user in the DB. When I migrate, how do I tell Rails to build UserNotification records for all the user users in the database?

Thanks for walking me through this. I haven't had to create a model like this before in Rails.

Upvotes: 1

Views: 538

Answers (1)

Keith Gaddis
Keith Gaddis

Reputation: 4113

This is the kind of thing you do in an after_create:

class User < ActiveRecord::Base

  belongs_to :user_notification
  after_create :create_user_notification


  def create_user_notification
    #additional logic probably needed per app requirements
    user_notification.create
  end
end

In your migration, you just need to iterate your existing users and call #create_user_notification

Upvotes: 1

Related Questions