Jump to content

The ultimate community for Ruby on Rails developers.


Creating a modular "messaging" component in Rails application

ruby rails ruby on rails controller model relationships database

  • Please log in to reply
1 reply to this topic

#1 keenanpayne



  • Members
  • 2 posts

Posted 12 December 2013 - 02:46 AM

Hello everybody! 


So I am creating a web application that has the following architecture: 



# Project Components
  resources :projects do
    resources :messages

    resources :lists do
      resources :tasks

So for each project, you can have multiple messages, as well as multiple to-do lists. Then for each to-do list, you can have multiple tasks. 


However, I am ultimately want to do something like this: 

# Project Components
  resources :projects do
    resources :messages

    resources :lists do
      resources :tasks do
         resources :messages

I want to add messaging to each one of my tasks. I know this would be super easy to scaffold, but in order to not create duplicate files and database tables, what would be the best way to accomplish this? 


What throws me off is that in my messages table, I have a foreign key project_id, and in order to have a message relate to a task, I would need a foreign key task_id

create_table "messages", :force => true do |t|
    t.string   "from"
    t.text     "body"
    t.integer  "project_id"
    t.datetime "created_at", :null => false
    t.datetime "updated_at", :null => false

So what I want to do is have only one set of messages models, views, and controllers, but have them somehow relate to projects as well as tasks. 


Does this make sense to anyone? And if so, is it possible? I'm not opposed to creating like messages-projects and messages-tasks or whatever, but if I can reduce code and files, that would be great to do. 

#2 Vasspilka



  • Members
  • 14 posts

Posted 26 December 2013 - 03:28 PM

You seem to be looking for Polymorphic Assosiations.


How it works?


Instead of adding just a project_id you add a messageable_id (integer) and a messageable_type (string) the messageable_type should be the items Model name e.g. "Project" or "Task" and the messageable_id should be the id of the item e.g. "1" ,"3".


Then with the right assosiation in the Models. You should have what you want :)


You can see a live example in my opensourced Project.


The migration

The polymorphic model

A commentable model


And a Video for RailCasts (might be outdated)


Edit: Also this would be best suited in the Models section  ;) .

  • james likes this

Also tagged with one or more of these keywords: ruby, rails, ruby on rails, controller, model, relationships, database

0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users