ruby-on-rails - Rails - Couldn't find Variant without an ID
问题描述
I am facing this error Couldn't find Variant without an ID
I don't get what is wrong :(
Stock belongs_to :variant
Variant has_many :stocks and belongs_to :product
Product
has_many :variants, inverse_of: :product, dependent: :destroy
has_many :stocks, through: :variants
accepts_nested_attributes_for :variants
stock.html.erb
<%= simple_form_for(Stock.new, url: admin_stocks_path) do |f| %>
<%= f.select :variant_id, options_from_collection_for_select(@product.variants, :id, :size),required: true %>
<%= f.input :quantity, required: true %>
<%= f.submit %>
<% end %>
stocks_controller.rb
class StocksController < ApplicationController
def show
@stock = Stock.find(params[:id])
end
def index
@stocks = Stock.all
@variants = Variant.all
end
def new
@stock = Stock.new
@product = Product.find(params[:product_id])
@variants = @product.variants
end
def create
find_variant
@product = @variant.product
@stock = Stock.new(stock_params)
if @stock.save
redirect_to stock_product_path(@product)
else
redirect_to stock_product_path(@product), alert: "Woops"
end
end
private
def stock_params
params.require(:stock).permit(:id, :quantity, :variant_id )
end
def find_variant
@variant = Variant.find(params[:variant_id])
end
end
I did fake the find_variant
method with Variant.find(2)
and it was working...
Why I can't find the :variant_id
?
here is my table stocks from my schema.rb
create_table "stocks", force: :cascade do |t|
t.integer "quantity"
t.bigint "variant_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["variant_id"], name: "index_stocks_on_variant_id"
end
解决方案
params[:variant_id]
will not be the value. You meant stock_params[:variant_id]
推荐阅读
- c - DMC 编译器 - C 中的“未加载浮点”错误
- python - flask_uploads:ImportError:无法导入名称“secure_filename”
- shell - UNIX:从分隔的文本文件创建表格格式的输出
- angular - Angular 如何在不同的单元测试中更新模拟数据
- c++ - 以分钟为单位查找本地时区与 GMT 的差异
- r - 从 excel 和 R 映射数据集
- javascript - 如何在javascript中的数组内添加字典
- javascript - 我必须在元素上注册哪种事件类型以跟踪添加子元素
- visual-studio-code - 如何将诸如控制向上/向下的emacs添加到vscode?
- vba - 防止访问表单被刷新