大家。我试图将每个产品与他的类别联系起来。但是有一些错误。
所以,起初。 以下是我的产品和类别迁移:
class CreateProducts < ActiveRecord::Migration
def change
create_table :products do |t|
t.belongs_to :categoty, index: true
t.string :title
t.string :category
t.text :description
t.string :image_url
t.decimal :price, precision: 8, scale: 2
t.timestamps
end
end
end
class CreateCategories < ActiveRecord::Migration
def change
create_table :categories do |t|
t.references :product
t.string :name
t.timestamps null: false
end
end
end
它们都在模型中有关联(产品为belongs_to
,类别为has_many
。
我已将表格与此类别的产品相关联:
<div class="field">
<%= f.collection_select :category, Category.all, :id, :name %>
</div>
当我试图保存产品时出现错误: 类别(#XXXX)预期,得到String(#XXXX)。
那么,我做错了什么?
此外,这是我的控制器。
class ProductsController < ApplicationController
before_action :set_product, only: [:show, :edit, :update, :destroy]
# GET /products
# GET /products.json
def index
@products = Product.all
end
# GET /products/1
# GET /products/1.json
def show
end
# GET /products/new
def new
@product = Product.new
end
# GET /products/1/edit
def edit
end
# POST /products
# POST /products.json
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
# PATCH/PUT /products/1
# PATCH/PUT /products/1.json
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
# DELETE /products/1
# DELETE /products/1.json
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
# Use callbacks to share common setup or constraints between actions.
def set_product
@product = Product.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def product_params
params.require(:product).permit(:title, :category, :description, :image_url, :price)
end
end
答案 0 :(得分:0)
在数据库迁移文件中,您有字段categoty
,并且您在控制器中使用category_id
。只需将字段更改为数据库中的category
,以确保它与正确的模型相关联。