Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby-on-rails-4/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails insert语句中缺少表中的字段_Ruby On Rails_Ruby On Rails 4 - Fatal编程技术网

Ruby on rails insert语句中缺少表中的字段

Ruby on rails insert语句中缺少表中的字段,ruby-on-rails,ruby-on-rails-4,Ruby On Rails,Ruby On Rails 4,尝试创建新行(product)时,create方法生成的INSERT语句缺少声明为NOTNULL的product_type_id字段。我不明白Rails为什么不在insert语句中包含product\u type\u id字段 我在尝试保存产品时遇到以下错误 ActiveRecord::语句在Admin::ProductsController#create中无效 Mysql2::错误:字段“product\u type\u id”没有默认值:INSERT INTOproducts(品牌标识,在创

尝试创建新行(product)时,create方法生成的INSERT语句缺少声明为NOTNULL的product_type_id字段。我不明白Rails为什么不在insert语句中包含product\u type\u id字段

我在尝试保存产品时遇到以下错误

ActiveRecord::语句在Admin::ProductsController#create中无效

Mysql2::错误:字段“product\u type\u id”没有默认值:INSERT INTO
products
品牌标识
创建,
说明
图像库
媒体嵌入
msrp
名称
价格覆盖
缩略图描述
更新
供应商库存单位
年份)值(9,“2014-08-31 16:45:50”,“a”,“b”,“33.0”,“a”,“3.0”,“2014-08-31 16:45:50”,“2015年”)

但是,products表具有product_type_id字段:

desc products
--------------

+-----------------+--------------+------+-----+---------+----------------+
| Field           | Type         | Null | Key | Default | Extra          |
+-----------------+--------------+------+-----+---------+----------------+
| id              | int(11)      | NO   | PRI | NULL    | auto_increment |
| product_type_id | int(11)      | NO   | MUL | NULL    |                |
| brand_id        | int(11)      | YES  | MUL | NULL    |                |
| name            | varchar(50)  | NO   |     | NULL    |                |
| thumbnail_desc  | varchar(200) | YES  |     | NULL    |                |
| description     | text         | NO   |     | NULL    |                |
| year            | int(11)      | YES  |     | NULL    |                |
| vendor_sku      | varchar(30)  | YES  | MUL | NULL    |                |
| msrp            | decimal(8,2) | YES  |     | NULL    |                |
| price_override  | decimal(8,2) | YES  |     | NULL    |                |
| visible         | tinyint(1)   | NO   |     | 1       |                |
| available       | tinyint(1)   | NO   |     | 1       |                |
| image_base      | varchar(255) | YES  |     | NULL    |                |
| video_source    | text         | YES  |     | NULL    |                |
| media_embed     | text         | YES  |     | NULL    |                |
| deleted_at      | datetime     | YES  |     | NULL    |                |
| created_at      | datetime     | YES  |     | NULL    |                |
| updated_at      | datetime     | YES  |     | NULL    |                |
+-----------------+--------------+------+-----+---------+----------------+
18 rows in set (0.01 sec)
请求参数显示产品类型id及其值:

Request

Parameters:

{"utf8"=>"✓",
 "authenticity_token"=>"VT42eeLLT/pyQ05ycfU/PeK92LIQ1P7NpWcPDOuOvsg=",
 "product"=>{"year"=>"2015",
 "brand_id"=>"9",
 "name"=>"a",
 "description"=>"",
 "thumbnail_desc"=>"",
 "category_ids"=>["",
 "29"],
 "product_class_ids"=>[""],
 "image_base"=>"a",
 "media_embed"=>"b",
 "vendor_sku"=>"",
 "msrp"=>"33",
 "price_override"=>"3",
 "visible"=>"1",
 "available"=>"1"},
 "commit"=>"Create Backpack",
 "product_type_id"=>"39"}
产品型号:

class Product < ActiveRecord::Base

  belongs_to :brand
  belongs_to :product_type

  has_and_belongs_to_many :categories
  has_and_belongs_to_many :product_classes

  scope :sorted, lambda { order("name ASC") }
  scope :notdeleted, lambda { where(:deleted_at => nil) }

  def active
    deleted_at.nil?
  end

end
类产品nil)}
def激活
在0.0处删除?
结束
结束
ProductType模型:

class ProductType < ActiveRecord::Base

  has_many :product_classes
  has_many :products

  validates_presence_of :name

  scope :sorted, lambda { order("name ASC") }
  scope :notdeleted, lambda { where(:deleted_at => nil) }

  def active
     deleted_at.nil?
  end

  def active=(val)
     self.deleted_at = [nil, '', '0', false].member?(val) ? Time.now : nil
  end

end
class ProductTypenil)}
def激活
在0.0处删除?
结束
def活动=(val)
self.deleted_at=[nil',,'0',false]。成员?(val)?时间。现在:nil
结束
结束
:product_type_id符号在产品控制器的params.permit中声明:

class Admin::ProductsController < ApplicationController

  layout 'admin'

  before_action :confirm_logged_in
  before_action :get_product, only: [:edit, :update, :delete, :destroy]
  before_action :get_stuff,   only: [:new, :create, :edit, :update, :delete, :destroy]

  def index
    @product_types = ProductType.notdeleted.sorted
  end

  def show
    #redirect_to(:action => 'manage_products')
  end

  def new
    @product_type = ProductType.find(params[:product_type_id])
    @product = Product.new({:product_type_id => @product_type.id})
  end

  def create
    @product = Product.new(product_params)
    if @product.save
      flash[:notice] = 'Product created.'
      redirect_to(:action => 'index', :product_type_id => @product_type.id)
    else
      render("new")
    end
  end

  def edit
  end

  def update
    if @product.update(product_params)
      flash[:notice] = 'Product updated.'
      redirect_to(:action => 'manage_products', :product_type_id => @product_type.id)
    else
      render("edit")
    end
  end

  def delete
  end

  def destroy
    @product.update(deleted_at: Time.now, visible: 0, available: 0)
    flash[:notice] = "Product deleted."
    redirect_to(:action => 'manage_products', :product_type_id => @product_type.id)
  end

  def manage_products
    id = params[:product_type_id]
    @product_type = ProductType.find(id)

    if params[:include_deleted] 
      @products = @product_type.products.sorted
    else
      @products = @product_type.products.notdeleted.sorted
    end

    #logger.debug("The size of products is #{@products.size}")
  end

  private

    def get_product
      @product = Product.find(params[:id])
      logger.debug("The product type id is #{@product.product_type_id}")
      @product_type = ProductType.find(@product.product_type_id)
      logger.debug("The product type is #{@product_type.name}")
      logger.debug("The product type has price is #{@product_type.has_price}")
    end

    def get_stuff
      @brands = Brand.sorted
      @categories = Category.sorted
    end

  def product_params
    params.require(:product).permit( :product_type_id, :brand_id, :name, :thumbnail_desc, :description, :year, :vendor_sku,
     :msrp, :price_override, :visible, :available, :image_base, :media_embed, :active, 
     :category_ids => [], :product_class_ids => [])
  end

end
class Admin::ProductsController“管理_产品”)
结束
def新
@product\U type=ProductType.find(参数[:product\U type\U id])
@product=product.new({:product\u type\u id=>@product\u type.id})
结束
def创建
@产品=新产品(产品参数)
如果@product.save
flash[:notice]=“产品已创建。”
重定向到(:action=>'index',:product\u type\u id=>@product\u type.id)
其他的
呈现(“新”)
结束
结束
定义编辑
结束
def更新
if@product.update(产品参数)
flash[:notice]=“产品已更新。”
将_重定向到(:action=>‘manage_products’,:product_type_id=>@product_type.id)
其他的
呈现(“编辑”)
结束
结束
def删除
结束
def销毁
@product.update(已在:Time.now删除,可见:0,可用:0)
flash[:notice]=“产品已删除。”
将_重定向到(:action=>‘manage_products’,:product_type_id=>@product_type.id)
结束
def管理产品
id=参数[:产品类型\u id]
@产品类型=产品类型。查找(id)
如果参数[:包含_已删除]
@products=@product\u type.products.sorted
其他的
@products=@product\u type.products.notdeleted.sorted
结束
#debug(“产品的大小为#{@products.size}”)
结束
私有的
def get_产品
@product=product.find(参数[:id])
debug(“产品类型id为#{@product.product_type_id}”)
@product\u type=ProductType.find(@product.product\u type\u id)
debug(“产品类型为#{@product_type.name}”)
debug(“产品类型has price为#{@product_type.has_price}”)
结束
def获取_内容
@品牌=品牌
@categories=Category.sorted
结束
def产品参数
参数要求(:产品)。许可(:产品类型id,:品牌id,:名称,:缩略图描述,:描述,:年份,:供应商sku,
:msrp、:price\u override、:visible、:available、:image\u base、:media\u embed、:active、,
:类别\标识=>[],:产品\类别\标识=>[])
结束
结束
new.html.erb

<% @page_title = "Create #{@product_type.name}" %>

<% content_for(:navigation) do -%>
    <p><a href="<%= admin_products_path %>"><img src="/assets/layout/icons/arrow_left.png" alt="Back" /> Back to <%= @product_type.name   %> List</a></p>
<% end -%>

<%= yield :navigation %>

  <%= form_for([:admin, @product], :url => {:action => 'create', :product_type_id => @product_type.id}) do |form| %>

  <%= render :partial => 'form', :locals => {:form => form} %>

  <div class="form-buttons">
    <%= submit_tag("Create #{@product_type.name}") %>
  </div>

  <% end %>

<%= yield :navigation %>

{:action=>'create',:product_type_id=>@product_type.id})do | form |%> 'form',:locals=>{:form=>form}%>
最后是_form.html.erb

  <% if @product.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@product.errors.count, "error") %> prohibited this page from being saved:</h2>
       <%= error_messages_for(@product) %>
    </div>
  <% end %>

<table cellpadding="0" cellspacing="0" class="admintable">
   <tr> 
    <th>Year</th>
    <td><%= form.text_field :year, :size => 5 %></td>
  </tr>
  <tr>
    <th>Brand</th>
    <td><%= form.select(:brand_id, @brands.map {|b| [b.name, b.id]}) %></td>
  </tr>
  <tr>
    <th>Product Name</th>
    <td><%= form.text_field :name, :size => 30 %></td>
  </tr>
  <tr> 
    <th>Description</th>
    <td><%= form.text_area :description, :cols => 60, :rows => 30 %></td>
  </tr>
  <tr> 
    <th>Thumbnail Description</th>
    <td><%= form.text_area :thumbnail_desc, :cols => 60, :rows => 5 %></td>
  </tr>
  <tr> 
    <th>Categories</th>
    <td>
    <%= form.collection_select :category_ids, Category.sorted, :id, :name, {}, {:multiple => true, include_blank: true, :size => 20 } %>
    </td>
  </tr>

  <tr> 
    <th>Product Class</th>
    <td>
    <%= form.collection_select :product_class_ids, ProductClass.options_for_select(@product.product_type_id), :id, :name, {}, {:multiple => true, include_blank: true, :size => 4 } %>
    </td>
  </tr>

  <tr> 
    <th>Image Base</th>
    <td><%= form.text_field :image_base, :size => 40 %></td>
  </tr>

  <tr> 
    <th>Media Embed Code</th>
    <td><%= form.text_area :media_embed, :cols => 60, :rows => 5 %></td>
  </tr>

  <tr> 
    <th>Vendor SKU</th>
    <td><%= form.text_field :vendor_sku, :size => 30 %></td>
  </tr>

  <% if @product_type.has_price? -%>
  <tr> 
    <th>MSRP</th>
    <td><%= form.text_field :msrp, :size => 5 %></td>
  </tr>

  <tr> 
    <th>BW Price</th>
    <td><%= form.text_field :price_override, :size => 5 %></td>
  </tr>
  <% end -%>

  <tr>
    <th>Visible?</th>
    <td><%= form.check_box :visible %></td>
  </tr>

  <tr>
    <th>Available?</th>
    <td><%= form.check_box :available %></td>
  </tr>

  <% unless @product.active -%>
  <tr>
    <th>Active</th>
    <td><%= form.check_box :active %></td>
  </tr>

  <% end -%>

</table>

禁止保存此页面:
年
5 %>
烙印
品名
30 %>
描述
60,:行=>30%>
缩略图描述
60,:行=>5%>
类别
true,包含_blank:true,:size=>20}%>
产品类别
true,包含_blank:true,:size=>4}%>
图像库
40 %>
媒体嵌入代码
60,:行=>5%>
供应商SKU
30 %>
MSRP
5 %>
BW价格
5 %>
看得见的
有空吗?
活跃的

我认为您应该重新订购产品类型id,如下所示:

"price_override"=>"3",
"visible"=>"1",
"available"=>"1",
"product_type_id"=>"39"},
"commit"=>"Create Backpack"

要将缺少的字段放入insert语句,我必须在表单中包含该值并将其隐藏:

  <% if @product.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@product.errors.count, "error") %> prohibited this page from being saved:</h2>
       <%= error_messages_for(@product) %>
    </div>
  <% end %>

<%= form.hidden_field :product_type_id, :value => @product_type.id %>

<table cellpadding="0" cellspacing="0" class="admintable">
   <tr> 
    <th>Year</th>
    <td><%= form.text_field :year, :size => 5 %></td>
  </tr>

谢谢Alex,让我走上正轨。

谢谢你的回答。在应用程序中,我在哪里指定参数的顺序?如果我没有完全弄错,应该是:
Request/parameters
我尝试在表单中使用隐藏字段,以便参数在跟踪中看起来像这样:Request Param计时器:{“utf8”=>“✓", "真实性标识“=>”VT42eeLLT/pyQ05ycfU/PeK92LIQ1P7NpWcPDOuOvsg=“,”产品“=>{”年份“=>”2015”,“品牌id“=>”9”,“名称“=>”a”,“说明“=>”b“,”缩略图描述“=>”c“,”类别id“=>[”,”29“,”产品类别_
    @product_type = ProductType.find(params[:product_type_id])