2

I have a table called Notification. This table has the following fields :id , :user_id , :foreign_id , :type

I want to associate Notifications with other tables like Friend , Quiz , Sport , Trip using the foreign key field :foreign_id, so that I can store different types of notifications in a generic way. I would like to store what type of notification in the :type database column such as "Friend" or "Quiz" and so on.

What is the best way to achieve something like this in Rails?

2 Answers 2

3

My guess is what you are looking for is called Polymorphic Associations

Sign up to request clarification or add additional context in comments.

Comments

1

You can store class name of the associated object as a string in object_type (or however you name it) field, that allows you to retrieve associated object like that:

# create new notification for quiz
Notification.create(user_id: user.id, foreign_id: quiz.id, object_type: quiz.class.to_s)

# load associated object for notification
associated_object = notification.object_type.constantize.find(notification.foreign_id)

2 Comments

Are the column names :foreign_id , :object_type built-in conventions?
No, they aren't. In fact you'd better use Polymorphic Associations as Art Shayderov suggested. It will be a better solution. Approach I suggested is more robust and may be not as good in actual project. See this Railscast for nice explanation of polymorphic associations.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.