5

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

次に、2つのフィールドを持つtvshowlinkepisodeというテーブルがあります:idShow、idEpisodeしたがって、2つのテーブルとそれらの間の結合(多対多の関係)がありますが、結合は非標準の外部キーを使用します。私が最初に考えたのは、TvShowEpisodeLinkというモデルを作成することでしたが、主キーがありません。外部キーは非標準であるため、set_foreign_keyを使用して、ある程度制御できるという考え方でした。最終的には、TvShow.find(:last).episodesやEpisode.find(:last).tv_showのようなものを言いたいです。どうやってそこまで行くの?

4

4 に答える 4

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

:foreign_key オプションは、リンクの「こちら側」のクラスの ID である列を指定するのに対し、:association_foreign_key は、リンクの「反対側」のクラスの ID である列を指定することに注意してください。

これをアルバロの答えと比較してください。このパターンは、リンクを表すために不要なオブジェクトのインスタンス化を避ける必要があります。

于 2009-07-24T22:13:24.177 に答える
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
于 2009-07-24T21:09:22.467 に答える
0

これにより、テーブルビューを設定する必要はありません。実際には、テーブルビューは「TheRailsWay」ではありません。

これを試して:

>> 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">]

次に、次のようなことを行うことができます。

e = Episode.find(1)
TvShow.find(1). episodes << e
#=> this make the proper association
于 2009-07-24T21:31:23.810 に答える
0

この関係は 1 対多であるため、テーブルで belongs_to/has__many 関係を使用する必要があります。データベースにビューがある場合、テーブルのビューによって非標準の外部キーをマスクできます。

それがあなたが必要とするものに100%適合するかどうかはわかりませんが、少なくともアイデアが得られることを願っています.

于 2009-07-24T20:31:17.347 に答える