ActiveRecord加入遗留数据库的表

nix*_*mus 5 ruby database legacy activerecord ruby-on-rails

我有一个遗留数据库,我正在努力让ActiveRecord使用.我遇到了连接表的问题.我有以下内容:

class TvShow < ActiveRecord::Base

  set_table_name "tvshow"
  set_primary_key "idShow"

end

class Episode < ActiveRecord::Base
  set_table_name "episode"
  set_primary_key "idEpisode"
end
Run Code Online (Sandbox Code Playgroud)

然后我有一个名为tvshowlinkepisode的表有2个字段:idShow,idEpisode所以我有2个表和它们之间的连接(所以有多对多关系),但是连接使用非标准外键.我的第一个想法是创建一个名为TvShowEpisodeLink的模型,但没有主键.我的想法是,由于外键是非标准的,我可以使用set_foreign_key并进行一些控制.最后我想说一些像TvShow.find(:last).episodes或Episode.find(:last).tv_show.我如何到达那里?

ani*_*mal 9

我相信你可以使用has_and_belongs_to_many的选项比Alvaro的回答更优雅,虽然他的回答非常好,并且会为你班级的任何客户提供相当相同的功能.

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
Run Code Online (Sandbox Code Playgroud)

请注意:foreign_key选项指定哪个列是链接"this side"上的类的id,而:association_foreign_key指定作为链接"另一侧"的类的id的列.

与Alvaro的回答相比,这种模式应避免实例化任何不必要的对象来表示链接.


小智 5

这项工作适合你......

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
Run Code Online (Sandbox Code Playgroud)