ActiveRecord Join table for legacy Database

随声附和 提交于 2019-12-03 15:20:18

I believe you can be slightly more elegant than Alvaro's answer using options to has_and_belongs_to_many, though his answer is perfectly fine and will result in fairly identical functionality for any clients of your class.

class TvShow < ActiveRecord::Base

  set_table_name "tvshow"
  set_primary_key "idShow"
  has_and_belong_to_many :episodes, 
                         :join_table => "tvshowlinkepisode", 
                         :foreign_key => "idShow",
                         :association_foreign_key => "idEpisode"

end

class Episode < ActiveRecord::Base
  set_table_name "episode"
  set_primary_key "idEpisode"
  has_and_belongs_to_many :tv_shows,
                          :join_table => "tvshowlinkepisode",
                          :foreign_key => "idEpisode",
                          :association_foreign_key => "idShow"
end

Note that the :foreign_key option specifies which column is the id for the class on "this side" of the link, while :association_foreign_key specifies the column that is the id for the class on the "other side" of the link.

Contrast this with Alvaro's answer, this pattern should avoid instantiation of any unnecessary objects to represent the link.

This work for you...

class TvShow < ActiveRecord::Base
  set_table_name "tvshow"
  set_primary_key "idShow"

  has_many :tv_show_link_episode, :foreign_key => 'idShow'
  has_many :episodes, :through => :tv_show_link_episode
end


class Episode < ActiveRecord::Base
  set_table_name "episode"
  set_primary_key "idEpisode"

  has_many :tv_show_link_episode, :foreign_key => 'idEpisode'
  has_many :tv_shows, :through => :tv_show_link_episode

end

class TvShowLinkEpisode  < ActiveRecord::Base
  set_table_name "tvshowlinkepisode"

    # the foreign key is named by the TvShowLinkEpisode field, 
    # the primary key name is for the primary key of the associated class
    belongs_to :tv_show, :foreign_key => 'idShow'
    belongs_to :episode, :foreign_key => 'idEpisode'
end

The relationship is one-to-many so you need to use the belongs_to/has__many relationship in the tables. If your database has views, you could mask the non-standard foreign keys by a view for the tables.

Not sure if that fits 100% what you need, but I hope it at least gives you an idea.

With this, you don't need to set table views, actually, tables views it's not "The Rails Way",

Try this:

>> TvShow.find(1).episodes 
#=> returns an array with [#<Episode idEpisode: 1, test: "Episode 1">]

>> Episode.find(1). tv_shows 
#=> returns an array with [#<TvShow idShow: 1, test: "tvshow 1">]

Then you can do some stuff like:

e = Episode.find(1)
TvShow.find(1). episodes << e
#=> this make the proper association
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!