ruby-on-rails – 为什么我的关联类型不匹配?
发布时间:2020-12-17 03:59:10 所属栏目:百科 来源:网络整理
导读:我是RoR的新手,遇到了让我疯狂的问题,我无法弄明白! 基本上,我已经创建了一个产品表单并添加了一个“供应商”选择字段,该字段找到了我的所有供应商,但现在当我尝试更新当前产品或创建新产品时,我收到以下错误: ActiveRecord::AssociationTypeMismatch in P
我是RoR的新手,遇到了让我疯狂的问题,我无法弄明白!
基本上,我已经创建了一个产品表单并添加了一个“供应商”选择字段,该字段找到了我的所有供应商,但现在当我尝试更新当前产品或创建新产品时,我收到以下错误: ActiveRecord::AssociationTypeMismatch in ProductsController#create Supplier(#2178099880) expected,got String(#2148287480) 我理解错误告诉我的是什么,但我不明白为什么.我也以同样的方式创建了产品类别的关联,工作正常! 此外,如果我添加验证以验证供应商的存在,即使选择了供应商,我也会收到“供应商不能为空”的错误. 真的很感激一些帮助! 在我的_form.html中,我有: <%= f.label :supplier %> <%= f.select(:supplier,Supplier.find(:all).collect {|c| [ c.name,c.id ]},:include_blank => true) %> 产品控制器: class ProductsController < ApplicationController # GET /products # GET /products.xml def index @products = Product.all respond_to do |format| format.html # index.html.erb format.xml { render :xml => @products } end end # GET /products/1 # GET /products/1.xml def show @product = Product.find(params[:id]) respond_to do |format| format.html # show.html.erb format.xml { render :xml => @product } end end # GET /products/new # GET /products/new.xml def new @product = Product.new respond_to do |format| format.html # new.html.erb format.xml { render :xml => @product } end end # GET /products/1/edit def edit @product = Product.find(params[:id]) end # POST /products # POST /products.xml def create @product = Product.new(params[:product]) respond_to do |format| if @product.save format.html { redirect_to(@product,:notice => 'Product was successfully created.') } format.xml { render :xml => @product,:status => :created,:location => @product } else format.html { render :action => "new" } format.xml { render :xml => @product.errors,:status => :unprocessable_entity } end end end # PUT /products/1 # PUT /products/1.xml def update @product = Product.find(params[:id]) respond_to do |format| if @product.update_attributes(params[:product]) format.html { redirect_to(@product,:notice => 'Product was successfully updated.') } format.xml { head :ok } else format.html { render :action => "edit" } format.xml { render :xml => @product.errors,:status => :unprocessable_entity } end end end # DELETE /products/1 # DELETE /products/1.xml def destroy @product = Product.find(params[:id]) @product.destroy respond_to do |format| format.html { redirect_to(products_url) } format.xml { head :ok } end end end 产品型号: class Product < ActiveRecord::Base belongs_to :supplier belongs_to :categories default_scope :order => 'product_number' validates_presence_of :product_name,:product_number,:category,:opening_order,:initial_cover,:country_of_origin,:supplier validates_uniqueness_of :product_number # Paperclip has_attached_file :image,:styles => { :medium => "300x300>",:thumb => "100x100>" } end 解决方法
而不是为供应商创建表单字段尝试为supplier_id创建它们:
<%= f.label :supplier_id %> <%= f.select(:supplier_id,:include_blank => true) %> (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |