投稿

3月, 2011の投稿を表示しています

rails3でHABTMが非推奨になってる

rails3でhas_and_belongs_to_manyを使ったActiveRecordを作ったらワーニングが出た。 DEPRECATION WARNING: Having additional attributes on the join table of a has_and_belongs_to_many association is deprecated and will be removed in Rails 3.1. Please use a has_many :through association instead.  rails3.1で消されちゃうよ、だと? うーん、そんな運命なのであれば使うのはやめよう。 で、対応としてはhas_many :throughを使えと。。。 ということで、こんなイメージの、 Hoges←(HABTM)→Moges HABTMでつないでいた多対多の関係であった2つのmodelをhas_many+throughにしてみる。 変更前 class Hoges < ActiveRecord::Base  has_and_belongs_to_many :moges  end class Moges < ActiveRecord::Base has_and_belongs_to_many :hoges end 変更後 class Hoges < ActiveRecord::Base has_many :hoges_moges has_many :moges, :through => :hoges_moges end class Moges < ActiveRecord::Base has_many :hoges_moges has_many :hoges, :through => :hoges_moges end has_and_belongs_to_manyを使うと自動的に中間テーブル?名を作ってSQLに組み込んでくれるって本に書いてあるけど、has_many使うと自動じゃなくなるのですか。そうですか。 自動じゃなくなるので、中間テーブルのmodelが必要になりました。HABTMでは存在しなかった中間テーブルのmodelクラスを作ってあげる。 で、has_manyに