Search code examples
ruby-on-railsruby-on-rails-3sqliteruby-on-rails-3.1models

Rails - one model that many others can use?


Running Rails 3.2.8 with SQLite (basic setup from current dl on rubyonrails.org)

If i have several models that I want to have an attribute of "notes" and all "notes" are String, should there only be one specific Note model, with all the other models referencing the Note model?

or

Does each model has to have its own attribute for "notes"?

If the first response, does that mean that for each relationship that references the "notes", do I need to create another class that defines that :through relationship? (ie tableOne, tableTwo, and tableThree all reference notes, then I would need to create additional classes tableOne_notes, tableTwo_notes, and tableThree_notes)

Is a polymorphic solution applicable?


Solution

  • If you want one 'notes' model that can serve the same purpose for many other models this would be a polymorphic relationship. This is actually true regardless of the application framework.

    In the specific case of rails implementation of polymorphic relationships for this example you would add a

    note_type 
    

    column in the notes model/table and in the Note model, using database migrations plus:

    belongs_to :notable, :polymorphic => true  
    

    in Note and then

    has_many notes, :as => notable` 
    

    in the other models that need the notes.

    See http://guides.rubyonrails.org/association_basics.html#polymorphic-associations for more.

    Frequent uses for Polymorphic relationships:

    • notes (as you are using)
    • update information (timestamp, ip address, user-agent, etc)
    • categories that are simple key-value lookups