SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    SitePoint Member
    Join Date
    Oct 2007
    Posts
    7
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    model associations: book, subject, author

    Hi.

    Does anyone know what the best way is to express the following association:

    Model A (subject), Model B(book), Model C(authors).

    Model B (book) belongs to many Model A(subjects).

    Model A(subjects) has many Model B (books)

    Model B (book) has many Model C(authors).

    any thoughts or links would be helpful.

    Thanks for anything. I've looked at the following, and have just gotten more confused:

    http://blog.hasmanythrough.com/2006/...orphic-through

    http://blog.hasmanythrough.com/2006/...many-dance-off

    although this is helpful, I'm not sure if I could use 'through' relationship, since Model C has no relation to Model A:

    http://mboffin.com/stuff/ruby-on-rai...ationships.png

  2. #2
    SitePoint Enthusiast
    Join Date
    May 2001
    Location
    Kaysville, UT
    Posts
    68
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Here's how I'd do it, use many-to-many relationships between books and authors and subjects and books:

    class Book < ActiveRecord::Base

    has_and_belongs_to_many :subjects, :authors

    end

    class Author < ActiveRecord::Base

    has_and_belongs_to_many :books

    end


    class Subject < ActiveRecord::Base

    has_and_belongs_to_many :books

    end


    This will require two join tables - subjects_books and authors_books, so you'd need a migration like:

    create_table :authors_books do |t|
    t.column :author_id, :integer
    t.column :book_id, :integer
    end

    create_table :subjects_books do |t|
    t.column :subject_id, :integer
    t.column :book_id, :integer
    end
    Spencer Uresk
    Rails App Hosting
    Cheap Hosting - Directory of hosting plans under $10/month!
    My blog: Tech and Java Articles

  3. #3
    SitePoint Member
    Join Date
    Oct 2007
    Posts
    7
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    thanks!

    Thanks for your help!


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •