产品有许多产品图片,产品图片属于产品。这是架构
class ExempleController extends Controller {
private $exemple;
public function __construct(ExempleRepositoryInterface $home) {
$this->exemple = $exemple;
}
public function test() {
$data = $this->exemple->getquery(); / you can pass a variable here if you want like this $this->exemple->getquery('variable');
// do stuff
}
以下是模型
create_table "product_images", force: :cascade do |t|
t.string "image"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "products", force: :cascade do |t|
t.string "name"
t.integer "price"
t.boolean "availability"
t.text "about"
t.integer "ref"
t.string "texture"
t.string "dimensions"
t.string "shipping"
t.string "category"
t.string "notes"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "sizes", default: [], array: true
end
我正在尝试添加迁移,将product_id作为product_images表的外键引用
class ProductImage < ActiveRecord::Base
belongs_to :product
end
class Product < ActiveRecord::Base
has_many :product_images
end
这是错误
class AddForeignKeyToProductImages < ActiveRecord::Migration
def change
add_foreign_key :product_images, :products, column: :product_id
end
end
答案 0 :(得分:2)
应该有效:
rails g migration AddProductToProductImages
class AddProductToProductImages < ActiveRecord::Migration
def change
add_column :product_images, :product_id, :integer
add_foreign_key :product_images, :products
end
end
您还可以执行以下操作:
rails g migration AddProductRefToProductImages product:references
class AddProductToProductImages < ActiveRecord::Migration
def change
add_reference :product_images, :product, index: true, foreign_key: true
end
end
您可以查看API了解详情。
答案 1 :(得分:1)
删除“AddForeignKeyToProductImages”迁移文件。然后...
在控制台中运行此命令:
rails g migration AddProductToProductImages product:references
应该生成以下迁移。
class AddProductToProductImages < ActiveRecord::Migration
def change
add_reference :product_images, :product, index: true
end
end
然后运行bundle exec rake db:migrate