【发布时间】:2015-12-04 20:41:58
【问题描述】:
大家。我试图将每个产品与他的类别联系起来。但是有一些错误。
所以,一开始。 这是我的产品和类别迁移:
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),得到字符串(#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
【问题讨论】:
-
belongs_to :category将在产品表中添加 category_id,这将成功建立类别has_many :products关系。我们不需要类别表中的references :product。 -
感谢您的关注!现在我知道。但我仍然有一个错误。
-
请分享您的控制器操作以清楚了解您如何调用 save
-
您在
Product模型中有String类型的:category属性。如果还有Category模型相关,真的有必要吗?可能是引发异常的原因。 -
@Mareq 是对的。将其设为 category_id
<%= f.collection_select :category_id, Category.all, :id, :name %>。并将其添加到params.require(:product).permit(:title, :category_id,....中。
标签: ruby-on-rails ruby