【发布时间】:2019-06-07 20:15:48
【问题描述】:
我希望根据品牌添加所有产品, 我有一个品牌和产品的脚手架, 我生成这样的品牌:rails generate scaffold Brand brand:string 并生成产品 has_many 与品牌脚手架的关联: rails 生成脚手架 Product productname:string brand:references
我的品牌模型
class Brand < ApplicationRecord
has_many :products
end
产品型号
class Product < ApplicationRecord
belongs_to :brand
end
品牌迁移
class CreateBrands < ActiveRecord::Migration[5.2]
def change
create_table :brands do |t|
t.string :brandname
t.timestamps
end
end
end
产品迁移
class CreateProducts < ActiveRecord::Migration[5.2]
def change
create_table :products do |t|
t.string :productname
t.references :brand
t.timestamps
end
end
end
品牌控制者
class CreateProducts < ActiveRecord::Migration[5.2]
def change
create_table :products do |t|
t.string :productname
t.references :brand
t.timestamps
end
end
end
产品控制器
class ProductsController < ApplicationController
before_action :set_product, only: [:show, :edit, :update, :destroy]
def index
@products = Product.all
end
def new
@product = Product.new
end
def create
@product = Product.new(product_params)
respond_to do |format|
if @product.save
format.html { redirect_to @product, notice: 'Product was successfully created.' }
format.json { render :show, status: :created, location: @product }
else
format.html { render :new }
format.json { render json: @product.errors, status: :unprocessable_entity }
end
end
end
def update
respond_to do |format|
if @product.update(product_params)
format.html { redirect_to @product, notice: 'Product was successfully updated.' }
format.json { render :show, status: :ok, location: @product }
else
format.html { render :edit }
format.json { render json: @product.errors, status: :unprocessable_entity }
end
end
end
def destroy
@product.destroy
respond_to do |format|
format.html { redirect_to products_url, notice: 'Product was successfully destroyed.' }
format.json { head :no_content }
end
end
private.
def set_product
@product = Product.find(params[:id])
end
def product_params
params.require(:product).permit(:productname, :brand_id)
end
end
我成功地对品牌进行了粗略操作,但我根据品牌尝试了新产品,但出现错误: 1 个错误禁止保存此产品: 品牌必须存在
如何解决这个问题,谢谢建议
【问题讨论】:
标签: ruby-on-rails ruby