开发者

How to improve this association in Rails

hey guys I want to build a database and some association between them, below are some descriptions

  1. Drummer and Video are many-to-many association, because, sometimes, more than one drummer will appear on one video clip

  2. Cymbal and Video are only many-to-many association, same reason

  3. Event and Video are one-to-many, because it makes sense that one video only represent only one Event

so for the first two my solution is using two has-and-belongs-to-many association sign to the both side, and for the 3rd one i use simple one-to-many: here's the code:

class Drummer < ActiveRecord::Base
  has_and_belongs_to_many :videos
end

class Cymbal < ActiveRecord::Base
  has_and_belongs_to_many :videos
end

class Video < ActiveRecord::Base
  has_and_belongs_to_many :drummers
  has_and_belongs_to_many :cymbals
  belongs_to :event
end

class Event < ActiveRecord::Base
  has_many :videos
end

But I think the polymorphic is the better solutions, video should ap开发者_开发问答ply two many other models, but I don't know how to make a many-to-many polymorphic association, i already ask a question about this


What about this:

class Interpreter < ActiveRecord::Base
  belongs_to :video
end

class Drummer < Interpreter
end

class Cymbal < Interpreter
end

class Video < ActiveRecord::Base
  has_and_belongs_to_many :interpreters
  has_and_belongs_to_many :drummers
  has_and_belongs_to_many :cymbals
  belongs_to :event
end

class Event < ActiveRecord::Base
  has_many :videos
end

Video.first.interpreters should return all drumers and cymbals, while Video.first.drummers and Video.first.cymbals will return only corresponding models Cymbals and Drummers will share same database table interpreters


Have you watched this http://railscasts.com/episodes/154-polymorphic-association

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜