开发者

Setting a type for one side of a many-to-many association with a join model

I set up a public github app (see: https://github.com/greenplastik/testapp to download) to work through a problem I'm having with specifying a type on one side of a many-to-many association between two models, via a join model.

Given Person and Book models and a Book_Person join model, I want to be able to do the following:

@book = Book.first @book.people # lists people for book @book.authors # lists author-type people for book @book.editors # lists editor-type people for book开发者_如何学编程

and

@person = Person.first @person.books # lists books for people

This app was set up in part using the instructions found through Google. There's a link to those instructions in the README of my testapp.

I tried, as best I could, to remove the inconsistencies and typos. I can't get it to work.

Any help would be appreciated. I've included the sqlite database for easier testing on your end.


I'm sorry i haven't got time to post neither a full solution or a tested one, but this should at least put you on the right track..

The best way to achieve what you're looking for is with Single Table Inheritance used with a polymorphic relationship.

I'd suggest redefining Author and Editor to be subclasses of Person

As in

class Person < ActiveRecord::Base
  has_many :book_people
  has_many :books, :through => :book_people
end


class Author < Person
end

class Editor < Person
end

class BookPerson < ActiveRecord::Base
  belongs_to :person, :polymorphic => true
  belongs_to :book
end

class Book < ActiveRecord::Base
  has_many :book_people
  has_many :people, :through => :book_people
  has_many :authors, :through => :book_people, :source => :person, :source_type => "Author"
  has_many :editors, :through => :book_people, :source => :person, :source_type => "Editor"
end

However this would be suboptimal if a single person could fill all three roles. There's probably a way around that by using the same STI name for the three of them. But then you'd make it harder to query for all authors.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜