ユーザーと製品の2つのモデルがあります。3 番目のモデル、Location を追加します。
以下を使用して Location モデルを作成しました。rails generate model Location address:string
ガイドに従って、 app/models/model.rbを修正します
class Location < ActiveRecord::Base
belongs_to :localizable, polymorphic: true
end
class User < ActiveRecord::Base
has_one :location, as: :localizable
end
class Product < ActiveRecord::Base
has_one :location, as: :localizable
end
次に、場所の移行ファイルにforeign_keyとインデックスを追加します:
class CreateLocations < ActiveRecord::Migration
def change
create_table :locations do |t|
t.string :address
t.integer :localizable_id
t.string :localizable_type
t.timestamps
end
add_index :locations, [:localizable_id, :localizable_type]
end
end
でも思ったようにはいきません。Rails コンソールを使用すると、user.location
または を取得できませんproduct.location
。次のメッセージが返されます。
ActiveRecord::StatementInvalid:
SQLite3::SQLException: no such column: locations.localizable_id: SELECT "locations".* FROM "locations" WHERE "locations"."localizable_id" = ? AND "locations"."localizable_type" = ? ORDER BY "locations"."id" ASC LIMIT 1
t.integer :location_id
ユーザー移行ファイルと製品移行ファイルの両方に追加する必要がありますか?