Rails脚手架关联has_many错误:1个错误禁止保存此产品

时间:2019-01-13 17:31:28

标签: ruby-on-rails ruby

我希望根据品牌添加所有产品, 我有一个品牌和产品支架, 我生成这样的品牌:导轨生成脚手架品牌brand:string 并生成具有品牌支架的产品has_many关联: Rails生成支架产品名称:字符串品牌:引用

我的品牌模式

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个错误,禁止保存该产品: 品牌必须存在

如何解决此问题,谢谢您的建议

1 个答案:

答案 0 :(得分:1)

在创建产品之前,您应该具有品牌记录, 在创建产品时,您应该包括将与该产品相关的品牌 以及通过brand_id保存的信息(请参阅:t.references:brand)

在您的ProductsController.rb文件中添加@brands

  class ProductsController < ApplicationController
    before_action :set_product, only: [:show, :edit, :update, :destroy]

    def new
      @product     = Product.new
      @brand_list  = Brand.all.map { |c| [ "#{c.brandname} ", c.id] }
    end

  end

在您的用于创建产品添加字段以选择以下品牌的视图文件中为示例

  <%= f.select :brand_id, @brand_list, { include_blank: false } %>